babylon.max.js 4.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. (function universalModuleDefinition(root, factory) {
  4. var amdDependencies = [];
  5. var CANNON = root.CANNON;
  6. var OIMO = root.OIMO;
  7. if(typeof exports === 'object' && typeof module === 'object') {
  8. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  9. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. define("babylonjs", amdDependencies, factory);
  15. } else if(typeof exports === 'object') {
  16. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  17. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  18. exports["babylonjs"] = factory(CANNON,OIMO);
  19. } else {
  20. root["BABYLON"] = factory(CANNON,OIMO);
  21. }
  22. })(this, function(CANNON,OIMO) {
  23. CANNON = CANNON || this.CANNON;
  24. OIMO = OIMO || this.OIMO;
  25. "use strict";
  26. var BABYLON;
  27. (function (BABYLON) {
  28. /**
  29. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  30. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  31. */
  32. var EffectFallbacks = /** @class */ (function () {
  33. function EffectFallbacks() {
  34. this._defines = {};
  35. this._currentRank = 32;
  36. this._maxRank = -1;
  37. }
  38. /**
  39. * Removes the fallback from the bound mesh.
  40. */
  41. EffectFallbacks.prototype.unBindMesh = function () {
  42. this._mesh = null;
  43. };
  44. /**
  45. * Adds a fallback on the specified property.
  46. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  47. * @param define The name of the define in the shader
  48. */
  49. EffectFallbacks.prototype.addFallback = function (rank, define) {
  50. if (!this._defines[rank]) {
  51. if (rank < this._currentRank) {
  52. this._currentRank = rank;
  53. }
  54. if (rank > this._maxRank) {
  55. this._maxRank = rank;
  56. }
  57. this._defines[rank] = new Array();
  58. }
  59. this._defines[rank].push(define);
  60. };
  61. /**
  62. * Sets the mesh to use CPU skinning when needing to fallback.
  63. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  64. * @param mesh The mesh to use the fallbacks.
  65. */
  66. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  67. this._mesh = mesh;
  68. if (rank < this._currentRank) {
  69. this._currentRank = rank;
  70. }
  71. if (rank > this._maxRank) {
  72. this._maxRank = rank;
  73. }
  74. };
  75. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  76. /**
  77. * Checks to see if more fallbacks are still availible.
  78. */
  79. get: function () {
  80. return this._currentRank <= this._maxRank;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. /**
  86. * Removes the defines that shoould be removed when falling back.
  87. * @param currentDefines defines the current define statements for the shader.
  88. * @param effect defines the current effect we try to compile
  89. * @returns The resulting defines with defines of the current rank removed.
  90. */
  91. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  92. // First we try to switch to CPU skinning
  93. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  94. this._mesh.computeBonesUsingShaders = false;
  95. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  96. var scene = this._mesh.getScene();
  97. for (var index = 0; index < scene.meshes.length; index++) {
  98. var otherMesh = scene.meshes[index];
  99. if (!otherMesh.material) {
  100. continue;
  101. }
  102. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  103. continue;
  104. }
  105. if (otherMesh.material.getEffect() === effect) {
  106. otherMesh.computeBonesUsingShaders = false;
  107. }
  108. else {
  109. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  110. var subMesh = _a[_i];
  111. var subMeshEffect = subMesh.effect;
  112. if (subMeshEffect === effect) {
  113. otherMesh.computeBonesUsingShaders = false;
  114. break;
  115. }
  116. }
  117. }
  118. }
  119. }
  120. else {
  121. var currentFallbacks = this._defines[this._currentRank];
  122. if (currentFallbacks) {
  123. for (var index = 0; index < currentFallbacks.length; index++) {
  124. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  125. }
  126. }
  127. this._currentRank++;
  128. }
  129. return currentDefines;
  130. };
  131. return EffectFallbacks;
  132. }());
  133. BABYLON.EffectFallbacks = EffectFallbacks;
  134. /**
  135. * Options to be used when creating an effect.
  136. */
  137. var EffectCreationOptions = /** @class */ (function () {
  138. function EffectCreationOptions() {
  139. }
  140. return EffectCreationOptions;
  141. }());
  142. BABYLON.EffectCreationOptions = EffectCreationOptions;
  143. /**
  144. * Effect containing vertex and fragment shader that can be executed on an object.
  145. */
  146. var Effect = /** @class */ (function () {
  147. /**
  148. * Instantiates an effect.
  149. * An effect can be used to create/manage/execute vertex and fragment shaders.
  150. * @param baseName Name of the effect.
  151. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  152. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  153. * @param samplers List of sampler variables that will be passed to the shader.
  154. * @param engine Engine to be used to render the effect
  155. * @param defines Define statements to be added to the shader.
  156. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  157. * @param onCompiled Callback that will be called when the shader is compiled.
  158. * @param onError Callback that will be called if an error occurs during shader compilation.
  159. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  160. */
  161. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  162. if (samplers === void 0) { samplers = null; }
  163. if (defines === void 0) { defines = null; }
  164. if (fallbacks === void 0) { fallbacks = null; }
  165. if (onCompiled === void 0) { onCompiled = null; }
  166. if (onError === void 0) { onError = null; }
  167. var _this = this;
  168. /**
  169. * Unique ID of the effect.
  170. */
  171. this.uniqueId = 0;
  172. /**
  173. * Observable that will be called when the shader is compiled.
  174. */
  175. this.onCompileObservable = new BABYLON.Observable();
  176. /**
  177. * Observable that will be called if an error occurs during shader compilation.
  178. */
  179. this.onErrorObservable = new BABYLON.Observable();
  180. /**
  181. * Observable that will be called when effect is bound.
  182. */
  183. this.onBindObservable = new BABYLON.Observable();
  184. this._uniformBuffersNames = {};
  185. this._isReady = false;
  186. this._compilationError = "";
  187. this.name = baseName;
  188. if (attributesNamesOrOptions.attributes) {
  189. var options = attributesNamesOrOptions;
  190. this._engine = uniformsNamesOrEngine;
  191. this._attributesNames = options.attributes;
  192. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  193. this._samplers = options.samplers;
  194. this.defines = options.defines;
  195. this.onError = options.onError;
  196. this.onCompiled = options.onCompiled;
  197. this._fallbacks = options.fallbacks;
  198. this._indexParameters = options.indexParameters;
  199. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  200. if (options.uniformBuffersNames) {
  201. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  202. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  203. }
  204. }
  205. }
  206. else {
  207. this._engine = engine;
  208. this.defines = defines;
  209. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  210. this._samplers = samplers;
  211. this._attributesNames = attributesNamesOrOptions;
  212. this.onError = onError;
  213. this.onCompiled = onCompiled;
  214. this._indexParameters = indexParameters;
  215. this._fallbacks = fallbacks;
  216. }
  217. this.uniqueId = Effect._uniqueIdSeed++;
  218. var vertexSource;
  219. var fragmentSource;
  220. if (baseName.vertexElement) {
  221. vertexSource = document.getElementById(baseName.vertexElement);
  222. if (!vertexSource) {
  223. vertexSource = baseName.vertexElement;
  224. }
  225. }
  226. else {
  227. vertexSource = baseName.vertex || baseName;
  228. }
  229. if (baseName.fragmentElement) {
  230. fragmentSource = document.getElementById(baseName.fragmentElement);
  231. if (!fragmentSource) {
  232. fragmentSource = baseName.fragmentElement;
  233. }
  234. }
  235. else {
  236. fragmentSource = baseName.fragment || baseName;
  237. }
  238. this._loadVertexShader(vertexSource, function (vertexCode) {
  239. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  240. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  241. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  242. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  243. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  244. if (baseName) {
  245. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  246. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  247. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  248. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  249. }
  250. else {
  251. _this._vertexSourceCode = migratedVertexCode;
  252. _this._fragmentSourceCode = migratedFragmentCode;
  253. }
  254. _this._prepareEffect();
  255. });
  256. });
  257. });
  258. });
  259. });
  260. });
  261. }
  262. Object.defineProperty(Effect.prototype, "key", {
  263. /**
  264. * Unique key for this effect
  265. */
  266. get: function () {
  267. return this._key;
  268. },
  269. enumerable: true,
  270. configurable: true
  271. });
  272. /**
  273. * If the effect has been compiled and prepared.
  274. * @returns if the effect is compiled and prepared.
  275. */
  276. Effect.prototype.isReady = function () {
  277. return this._isReady;
  278. };
  279. /**
  280. * The engine the effect was initialized with.
  281. * @returns the engine.
  282. */
  283. Effect.prototype.getEngine = function () {
  284. return this._engine;
  285. };
  286. /**
  287. * The compiled webGL program for the effect
  288. * @returns the webGL program.
  289. */
  290. Effect.prototype.getProgram = function () {
  291. return this._program;
  292. };
  293. /**
  294. * The set of names of attribute variables for the shader.
  295. * @returns An array of attribute names.
  296. */
  297. Effect.prototype.getAttributesNames = function () {
  298. return this._attributesNames;
  299. };
  300. /**
  301. * Returns the attribute at the given index.
  302. * @param index The index of the attribute.
  303. * @returns The location of the attribute.
  304. */
  305. Effect.prototype.getAttributeLocation = function (index) {
  306. return this._attributes[index];
  307. };
  308. /**
  309. * Returns the attribute based on the name of the variable.
  310. * @param name of the attribute to look up.
  311. * @returns the attribute location.
  312. */
  313. Effect.prototype.getAttributeLocationByName = function (name) {
  314. var index = this._attributesNames.indexOf(name);
  315. return this._attributes[index];
  316. };
  317. /**
  318. * The number of attributes.
  319. * @returns the numnber of attributes.
  320. */
  321. Effect.prototype.getAttributesCount = function () {
  322. return this._attributes.length;
  323. };
  324. /**
  325. * Gets the index of a uniform variable.
  326. * @param uniformName of the uniform to look up.
  327. * @returns the index.
  328. */
  329. Effect.prototype.getUniformIndex = function (uniformName) {
  330. return this._uniformsNames.indexOf(uniformName);
  331. };
  332. /**
  333. * Returns the attribute based on the name of the variable.
  334. * @param uniformName of the uniform to look up.
  335. * @returns the location of the uniform.
  336. */
  337. Effect.prototype.getUniform = function (uniformName) {
  338. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  339. };
  340. /**
  341. * Returns an array of sampler variable names
  342. * @returns The array of sampler variable neames.
  343. */
  344. Effect.prototype.getSamplers = function () {
  345. return this._samplers;
  346. };
  347. /**
  348. * The error from the last compilation.
  349. * @returns the error string.
  350. */
  351. Effect.prototype.getCompilationError = function () {
  352. return this._compilationError;
  353. };
  354. /**
  355. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  356. * @param func The callback to be used.
  357. */
  358. Effect.prototype.executeWhenCompiled = function (func) {
  359. if (this.isReady()) {
  360. func(this);
  361. return;
  362. }
  363. this.onCompileObservable.add(function (effect) {
  364. func(effect);
  365. });
  366. };
  367. /** @ignore */
  368. Effect.prototype._loadVertexShader = function (vertex, callback) {
  369. if (BABYLON.Tools.IsWindowObjectExist()) {
  370. // DOM element ?
  371. if (vertex instanceof HTMLElement) {
  372. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  373. callback(vertexCode);
  374. return;
  375. }
  376. }
  377. // Base64 encoded ?
  378. if (vertex.substr(0, 7) === "base64:") {
  379. var vertexBinary = window.atob(vertex.substr(7));
  380. callback(vertexBinary);
  381. return;
  382. }
  383. // Is in local store ?
  384. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  385. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  386. return;
  387. }
  388. var vertexShaderUrl;
  389. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  390. vertexShaderUrl = vertex;
  391. }
  392. else {
  393. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  394. }
  395. // Vertex shader
  396. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  397. };
  398. /** @ignore */
  399. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  400. if (BABYLON.Tools.IsWindowObjectExist()) {
  401. // DOM element ?
  402. if (fragment instanceof HTMLElement) {
  403. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  404. callback(fragmentCode);
  405. return;
  406. }
  407. }
  408. // Base64 encoded ?
  409. if (fragment.substr(0, 7) === "base64:") {
  410. var fragmentBinary = window.atob(fragment.substr(7));
  411. callback(fragmentBinary);
  412. return;
  413. }
  414. // Is in local store ?
  415. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  416. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  417. return;
  418. }
  419. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  420. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  421. return;
  422. }
  423. var fragmentShaderUrl;
  424. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  425. fragmentShaderUrl = fragment;
  426. }
  427. else {
  428. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  429. }
  430. // Fragment shader
  431. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  432. };
  433. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  434. // Rebuild shaders source code
  435. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  436. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  437. vertexCode = prefix + vertexCode;
  438. fragmentCode = prefix + fragmentCode;
  439. // Number lines of shaders source code
  440. var i = 2;
  441. var regex = /\n/gm;
  442. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  443. i = 2;
  444. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  445. // Dump shaders name and formatted source code
  446. if (this.name.vertexElement) {
  447. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  448. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  449. }
  450. else if (this.name.vertex) {
  451. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  452. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  453. }
  454. else {
  455. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  456. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  457. }
  458. };
  459. ;
  460. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  461. var preparedSourceCode = this._processPrecision(sourceCode);
  462. if (this._engine.webGLVersion == 1) {
  463. callback(preparedSourceCode);
  464. return;
  465. }
  466. // Already converted
  467. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  468. callback(preparedSourceCode.replace("#version 300 es", ""));
  469. return;
  470. }
  471. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  472. // Remove extensions
  473. // #extension GL_OES_standard_derivatives : enable
  474. // #extension GL_EXT_shader_texture_lod : enable
  475. // #extension GL_EXT_frag_depth : enable
  476. // #extension GL_EXT_draw_buffers : require
  477. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  478. var result = preparedSourceCode.replace(regex, "");
  479. // Migrate to GLSL v300
  480. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  481. result = result.replace(/attribute[ \t]/g, "in ");
  482. result = result.replace(/[ \t]attribute/g, " in");
  483. if (isFragment) {
  484. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  485. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  486. result = result.replace(/texture2D\s*\(/g, "texture(");
  487. result = result.replace(/textureCube\s*\(/g, "texture(");
  488. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  489. result = result.replace(/gl_FragColor/g, "glFragColor");
  490. result = result.replace(/gl_FragData/g, "glFragData");
  491. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  492. }
  493. callback(result);
  494. };
  495. Effect.prototype._processIncludes = function (sourceCode, callback) {
  496. var _this = this;
  497. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  498. var match = regex.exec(sourceCode);
  499. var returnValue = new String(sourceCode);
  500. while (match != null) {
  501. var includeFile = match[1];
  502. // Uniform declaration
  503. if (includeFile.indexOf("__decl__") !== -1) {
  504. includeFile = includeFile.replace(/__decl__/, "");
  505. if (this._engine.supportsUniformBuffers) {
  506. includeFile = includeFile.replace(/Vertex/, "Ubo");
  507. includeFile = includeFile.replace(/Fragment/, "Ubo");
  508. }
  509. includeFile = includeFile + "Declaration";
  510. }
  511. if (Effect.IncludesShadersStore[includeFile]) {
  512. // Substitution
  513. var includeContent = Effect.IncludesShadersStore[includeFile];
  514. if (match[2]) {
  515. var splits = match[3].split(",");
  516. for (var index = 0; index < splits.length; index += 2) {
  517. var source = new RegExp(splits[index], "g");
  518. var dest = splits[index + 1];
  519. includeContent = includeContent.replace(source, dest);
  520. }
  521. }
  522. if (match[4]) {
  523. var indexString = match[5];
  524. if (indexString.indexOf("..") !== -1) {
  525. var indexSplits = indexString.split("..");
  526. var minIndex = parseInt(indexSplits[0]);
  527. var maxIndex = parseInt(indexSplits[1]);
  528. var sourceIncludeContent = includeContent.slice(0);
  529. includeContent = "";
  530. if (isNaN(maxIndex)) {
  531. maxIndex = this._indexParameters[indexSplits[1]];
  532. }
  533. for (var i = minIndex; i < maxIndex; i++) {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  541. }
  542. }
  543. else {
  544. if (!this._engine.supportsUniformBuffers) {
  545. // Ubo replacement
  546. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  547. return p1 + "{X}";
  548. });
  549. }
  550. includeContent = includeContent.replace(/\{X\}/g, indexString);
  551. }
  552. }
  553. // Replace
  554. returnValue = returnValue.replace(match[0], includeContent);
  555. }
  556. else {
  557. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  558. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  559. Effect.IncludesShadersStore[includeFile] = fileContent;
  560. _this._processIncludes(returnValue, callback);
  561. });
  562. return;
  563. }
  564. match = regex.exec(sourceCode);
  565. }
  566. callback(returnValue);
  567. };
  568. Effect.prototype._processPrecision = function (source) {
  569. if (source.indexOf("precision highp float") === -1) {
  570. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  571. source = "precision mediump float;\n" + source;
  572. }
  573. else {
  574. source = "precision highp float;\n" + source;
  575. }
  576. }
  577. else {
  578. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  579. source = source.replace("precision highp float", "precision mediump float");
  580. }
  581. }
  582. return source;
  583. };
  584. /**
  585. * Recompiles the webGL program
  586. * @param vertexSourceCode The source code for the vertex shader.
  587. * @param fragmentSourceCode The source code for the fragment shader.
  588. * @param onCompiled Callback called when completed.
  589. * @param onError Callback called on error.
  590. */
  591. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  592. var _this = this;
  593. this._isReady = false;
  594. this._vertexSourceCodeOverride = vertexSourceCode;
  595. this._fragmentSourceCodeOverride = fragmentSourceCode;
  596. this.onError = function (effect, error) {
  597. if (onError) {
  598. onError(error);
  599. }
  600. };
  601. this.onCompiled = function () {
  602. var scenes = _this.getEngine().scenes;
  603. for (var i = 0; i < scenes.length; i++) {
  604. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  605. }
  606. if (onCompiled) {
  607. onCompiled(_this._program);
  608. }
  609. };
  610. this._fallbacks = null;
  611. this._prepareEffect();
  612. };
  613. /**
  614. * Gets the uniform locations of the the specified variable names
  615. * @param names THe names of the variables to lookup.
  616. * @returns Array of locations in the same order as variable names.
  617. */
  618. Effect.prototype.getSpecificUniformLocations = function (names) {
  619. var engine = this._engine;
  620. return engine.getUniforms(this._program, names);
  621. };
  622. /**
  623. * Prepares the effect
  624. */
  625. Effect.prototype._prepareEffect = function () {
  626. var attributesNames = this._attributesNames;
  627. var defines = this.defines;
  628. var fallbacks = this._fallbacks;
  629. this._valueCache = {};
  630. var previousProgram = this._program;
  631. try {
  632. var engine = this._engine;
  633. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  634. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  635. }
  636. else {
  637. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  638. }
  639. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  640. if (engine.supportsUniformBuffers) {
  641. for (var name in this._uniformBuffersNames) {
  642. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  643. }
  644. }
  645. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  646. this._attributes = engine.getAttributes(this._program, attributesNames);
  647. var index;
  648. for (index = 0; index < this._samplers.length; index++) {
  649. var sampler = this.getUniform(this._samplers[index]);
  650. if (sampler == null) {
  651. this._samplers.splice(index, 1);
  652. index--;
  653. }
  654. }
  655. engine.bindSamplers(this);
  656. this._compilationError = "";
  657. this._isReady = true;
  658. if (this.onCompiled) {
  659. this.onCompiled(this);
  660. }
  661. this.onCompileObservable.notifyObservers(this);
  662. this.onCompileObservable.clear();
  663. // Unbind mesh reference in fallbacks
  664. if (this._fallbacks) {
  665. this._fallbacks.unBindMesh();
  666. }
  667. if (previousProgram) {
  668. this.getEngine()._deleteProgram(previousProgram);
  669. }
  670. }
  671. catch (e) {
  672. this._compilationError = e.message;
  673. // Let's go through fallbacks then
  674. BABYLON.Tools.Error("Unable to compile effect:");
  675. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  676. return " " + uniform;
  677. }));
  678. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  679. return " " + attribute;
  680. }));
  681. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  682. BABYLON.Tools.Error("Error: " + this._compilationError);
  683. if (previousProgram) {
  684. this._program = previousProgram;
  685. this._isReady = true;
  686. if (this.onError) {
  687. this.onError(this, this._compilationError);
  688. }
  689. this.onErrorObservable.notifyObservers(this);
  690. }
  691. if (fallbacks && fallbacks.isMoreFallbacks) {
  692. BABYLON.Tools.Error("Trying next fallback.");
  693. this.defines = fallbacks.reduce(this.defines, this);
  694. this._prepareEffect();
  695. }
  696. else {
  697. if (this.onError) {
  698. this.onError(this, this._compilationError);
  699. }
  700. this.onErrorObservable.notifyObservers(this);
  701. this.onErrorObservable.clear();
  702. // Unbind mesh reference in fallbacks
  703. if (this._fallbacks) {
  704. this._fallbacks.unBindMesh();
  705. }
  706. }
  707. }
  708. };
  709. Object.defineProperty(Effect.prototype, "isSupported", {
  710. /**
  711. * Checks if the effect is supported. (Must be called after compilation)
  712. */
  713. get: function () {
  714. return this._compilationError === "";
  715. },
  716. enumerable: true,
  717. configurable: true
  718. });
  719. /**
  720. * Binds a texture to the engine to be used as output of the shader.
  721. * @param channel Name of the output variable.
  722. * @param texture Texture to bind.
  723. */
  724. Effect.prototype._bindTexture = function (channel, texture) {
  725. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  726. };
  727. /**
  728. * Sets a texture on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setTexture = function (channel, texture) {
  733. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  737. * @param channel Name of the sampler variable.
  738. * @param texture Texture to set.
  739. */
  740. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  741. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  742. };
  743. /**
  744. * Sets an array of textures on the engine to be used in the shader.
  745. * @param channel Name of the variable.
  746. * @param textures Textures to set.
  747. */
  748. Effect.prototype.setTextureArray = function (channel, textures) {
  749. if (this._samplers.indexOf(channel + "Ex") === -1) {
  750. var initialPos = this._samplers.indexOf(channel);
  751. for (var index = 1; index < textures.length; index++) {
  752. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  753. }
  754. }
  755. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  756. };
  757. /**
  758. * 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)
  759. * @param channel Name of the sampler variable.
  760. * @param postProcess Post process to get the input texture from.
  761. */
  762. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  763. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  764. };
  765. /**
  766. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  767. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  768. * @param channel Name of the sampler variable.
  769. * @param postProcess Post process to get the output texture from.
  770. */
  771. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  772. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  773. };
  774. /** @ignore */
  775. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  776. var cache = this._valueCache[uniformName];
  777. var flag = matrix.updateFlag;
  778. if (cache !== undefined && cache === flag) {
  779. return false;
  780. }
  781. this._valueCache[uniformName] = flag;
  782. return true;
  783. };
  784. /** @ignore */
  785. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  786. var cache = this._valueCache[uniformName];
  787. if (!cache) {
  788. cache = [x, y];
  789. this._valueCache[uniformName] = cache;
  790. return true;
  791. }
  792. var changed = false;
  793. if (cache[0] !== x) {
  794. cache[0] = x;
  795. changed = true;
  796. }
  797. if (cache[1] !== y) {
  798. cache[1] = y;
  799. changed = true;
  800. }
  801. return changed;
  802. };
  803. /** @ignore */
  804. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y, z];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. if (cache[2] !== z) {
  821. cache[2] = z;
  822. changed = true;
  823. }
  824. return changed;
  825. };
  826. /** @ignore */
  827. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  828. var cache = this._valueCache[uniformName];
  829. if (!cache) {
  830. cache = [x, y, z, w];
  831. this._valueCache[uniformName] = cache;
  832. return true;
  833. }
  834. var changed = false;
  835. if (cache[0] !== x) {
  836. cache[0] = x;
  837. changed = true;
  838. }
  839. if (cache[1] !== y) {
  840. cache[1] = y;
  841. changed = true;
  842. }
  843. if (cache[2] !== z) {
  844. cache[2] = z;
  845. changed = true;
  846. }
  847. if (cache[3] !== w) {
  848. cache[3] = w;
  849. changed = true;
  850. }
  851. return changed;
  852. };
  853. /**
  854. * Binds a buffer to a uniform.
  855. * @param buffer Buffer to bind.
  856. * @param name Name of the uniform variable to bind to.
  857. */
  858. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  859. var bufferName = this._uniformBuffersNames[name];
  860. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  861. return;
  862. }
  863. Effect._baseCache[bufferName] = buffer;
  864. this._engine.bindUniformBufferBase(buffer, bufferName);
  865. };
  866. /**
  867. * Binds block to a uniform.
  868. * @param blockName Name of the block to bind.
  869. * @param index Index to bind.
  870. */
  871. Effect.prototype.bindUniformBlock = function (blockName, index) {
  872. this._engine.bindUniformBlock(this._program, blockName, index);
  873. };
  874. /**
  875. * Sets an interger value on a uniform variable.
  876. * @param uniformName Name of the variable.
  877. * @param value Value to be set.
  878. * @returns this effect.
  879. */
  880. Effect.prototype.setInt = function (uniformName, value) {
  881. var cache = this._valueCache[uniformName];
  882. if (cache !== undefined && cache === value)
  883. return this;
  884. this._valueCache[uniformName] = value;
  885. this._engine.setInt(this.getUniform(uniformName), value);
  886. return this;
  887. };
  888. /**
  889. * Sets an int array on a uniform variable.
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * 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)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray2 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray2(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * 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)
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setIntArray3 = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setIntArray3(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * 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)
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setIntArray4 = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setIntArray4(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * Sets an float array on a uniform variable.
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * 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)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * 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)
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * 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)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * Sets an array on a uniform variable.
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * 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)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray2 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray2(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * 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)
  1000. * @param uniformName Name of the variable.
  1001. * @param array array to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setArray3 = function (uniformName, array) {
  1005. this._valueCache[uniformName] = null;
  1006. this._engine.setArray3(this.getUniform(uniformName), array);
  1007. return this;
  1008. };
  1009. /**
  1010. * 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)
  1011. * @param uniformName Name of the variable.
  1012. * @param array array to be set.
  1013. * @returns this effect.
  1014. */
  1015. Effect.prototype.setArray4 = function (uniformName, array) {
  1016. this._valueCache[uniformName] = null;
  1017. this._engine.setArray4(this.getUniform(uniformName), array);
  1018. return this;
  1019. };
  1020. /**
  1021. * Sets matrices on a uniform variable.
  1022. * @param uniformName Name of the variable.
  1023. * @param matrices matrices to be set.
  1024. * @returns this effect.
  1025. */
  1026. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1027. if (!matrices) {
  1028. return this;
  1029. }
  1030. this._valueCache[uniformName] = null;
  1031. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1032. return this;
  1033. };
  1034. /**
  1035. * Sets matrix on a uniform variable.
  1036. * @param uniformName Name of the variable.
  1037. * @param matrix matrix to be set.
  1038. * @returns this effect.
  1039. */
  1040. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1041. if (this._cacheMatrix(uniformName, matrix)) {
  1042. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1043. }
  1044. return this;
  1045. };
  1046. /**
  1047. * 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)
  1048. * @param uniformName Name of the variable.
  1049. * @param matrix matrix to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1053. this._valueCache[uniformName] = null;
  1054. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1055. return this;
  1056. };
  1057. /**
  1058. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1059. * @param uniformName Name of the variable.
  1060. * @param matrix matrix to be set.
  1061. * @returns this effect.
  1062. */
  1063. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1064. this._valueCache[uniformName] = null;
  1065. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1066. return this;
  1067. };
  1068. /**
  1069. * Sets a float on a uniform variable.
  1070. * @param uniformName Name of the variable.
  1071. * @param value value to be set.
  1072. * @returns this effect.
  1073. */
  1074. Effect.prototype.setFloat = function (uniformName, value) {
  1075. var cache = this._valueCache[uniformName];
  1076. if (cache !== undefined && cache === value)
  1077. return this;
  1078. this._valueCache[uniformName] = value;
  1079. this._engine.setFloat(this.getUniform(uniformName), value);
  1080. return this;
  1081. };
  1082. /**
  1083. * Sets a boolean on a uniform variable.
  1084. * @param uniformName Name of the variable.
  1085. * @param bool value to be set.
  1086. * @returns this effect.
  1087. */
  1088. Effect.prototype.setBool = function (uniformName, bool) {
  1089. var cache = this._valueCache[uniformName];
  1090. if (cache !== undefined && cache === bool)
  1091. return this;
  1092. this._valueCache[uniformName] = bool;
  1093. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1094. return this;
  1095. };
  1096. /**
  1097. * Sets a Vector2 on a uniform variable.
  1098. * @param uniformName Name of the variable.
  1099. * @param vector2 vector2 to be set.
  1100. * @returns this effect.
  1101. */
  1102. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1103. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1104. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1105. }
  1106. return this;
  1107. };
  1108. /**
  1109. * Sets a float2 on a uniform variable.
  1110. * @param uniformName Name of the variable.
  1111. * @param x First float in float2.
  1112. * @param y Second float in float2.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1116. if (this._cacheFloat2(uniformName, x, y)) {
  1117. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1118. }
  1119. return this;
  1120. };
  1121. /**
  1122. * Sets a Vector3 on a uniform variable.
  1123. * @param uniformName Name of the variable.
  1124. * @param vector3 Value to be set.
  1125. * @returns this effect.
  1126. */
  1127. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1128. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1129. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1130. }
  1131. return this;
  1132. };
  1133. /**
  1134. * Sets a float3 on a uniform variable.
  1135. * @param uniformName Name of the variable.
  1136. * @param x First float in float3.
  1137. * @param y Second float in float3.
  1138. * @param z Third float in float3.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1142. if (this._cacheFloat3(uniformName, x, y, z)) {
  1143. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1144. }
  1145. return this;
  1146. };
  1147. /**
  1148. * Sets a Vector4 on a uniform variable.
  1149. * @param uniformName Name of the variable.
  1150. * @param vector4 Value to be set.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1154. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1155. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1156. }
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets a float4 on a uniform variable.
  1161. * @param uniformName Name of the variable.
  1162. * @param x First float in float4.
  1163. * @param y Second float in float4.
  1164. * @param z Third float in float4.
  1165. * @param w Fourth float in float4.
  1166. * @returns this effect.
  1167. */
  1168. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1169. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1170. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1171. }
  1172. return this;
  1173. };
  1174. /**
  1175. * Sets a Color3 on a uniform variable.
  1176. * @param uniformName Name of the variable.
  1177. * @param color3 Value to be set.
  1178. * @returns this effect.
  1179. */
  1180. Effect.prototype.setColor3 = function (uniformName, color3) {
  1181. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1182. this._engine.setColor3(this.getUniform(uniformName), color3);
  1183. }
  1184. return this;
  1185. };
  1186. /**
  1187. * Sets a Color4 on a uniform variable.
  1188. * @param uniformName Name of the variable.
  1189. * @param color3 Value to be set.
  1190. * @param alpha Alpha value to be set.
  1191. * @returns this effect.
  1192. */
  1193. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1194. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1195. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1196. }
  1197. return this;
  1198. };
  1199. /**
  1200. * Sets a Color4 on a uniform variable
  1201. * @param uniformName defines the name of the variable
  1202. * @param color4 defines the value to be set
  1203. * @returns this effect.
  1204. */
  1205. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1206. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1207. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1208. }
  1209. return this;
  1210. };
  1211. /**
  1212. * Resets the cache of effects.
  1213. */
  1214. Effect.ResetCache = function () {
  1215. Effect._baseCache = {};
  1216. };
  1217. Effect._uniqueIdSeed = 0;
  1218. Effect._baseCache = {};
  1219. /**
  1220. * Store of each shader (The can be looked up using effect.key)
  1221. */
  1222. Effect.ShadersStore = {};
  1223. /**
  1224. * Store of each included file for a shader (The can be looked up using effect.key)
  1225. */
  1226. Effect.IncludesShadersStore = {};
  1227. return Effect;
  1228. }());
  1229. BABYLON.Effect = Effect;
  1230. })(BABYLON || (BABYLON = {}));
  1231. //# sourceMappingURL=babylon.effect.js.map
  1232. "use strict";
  1233. //# sourceMappingURL=babylon.types.js.map
  1234. "use strict";
  1235. var BABYLON;
  1236. (function (BABYLON) {
  1237. var KeyboardEventTypes = /** @class */ (function () {
  1238. function KeyboardEventTypes() {
  1239. }
  1240. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1241. get: function () {
  1242. return KeyboardEventTypes._KEYDOWN;
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1248. get: function () {
  1249. return KeyboardEventTypes._KEYUP;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. KeyboardEventTypes._KEYDOWN = 0x01;
  1255. KeyboardEventTypes._KEYUP = 0x02;
  1256. return KeyboardEventTypes;
  1257. }());
  1258. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1259. var KeyboardInfo = /** @class */ (function () {
  1260. function KeyboardInfo(type, event) {
  1261. this.type = type;
  1262. this.event = event;
  1263. }
  1264. return KeyboardInfo;
  1265. }());
  1266. BABYLON.KeyboardInfo = KeyboardInfo;
  1267. /**
  1268. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1269. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1270. */
  1271. var KeyboardInfoPre = /** @class */ (function (_super) {
  1272. __extends(KeyboardInfoPre, _super);
  1273. function KeyboardInfoPre(type, event) {
  1274. var _this = _super.call(this, type, event) || this;
  1275. _this.skipOnPointerObservable = false;
  1276. return _this;
  1277. }
  1278. return KeyboardInfoPre;
  1279. }(KeyboardInfo));
  1280. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1281. })(BABYLON || (BABYLON = {}));
  1282. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1283. "use strict";
  1284. var BABYLON;
  1285. (function (BABYLON) {
  1286. var PointerEventTypes = /** @class */ (function () {
  1287. function PointerEventTypes() {
  1288. }
  1289. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERDOWN;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1297. get: function () {
  1298. return PointerEventTypes._POINTERUP;
  1299. },
  1300. enumerable: true,
  1301. configurable: true
  1302. });
  1303. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1304. get: function () {
  1305. return PointerEventTypes._POINTERMOVE;
  1306. },
  1307. enumerable: true,
  1308. configurable: true
  1309. });
  1310. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1311. get: function () {
  1312. return PointerEventTypes._POINTERWHEEL;
  1313. },
  1314. enumerable: true,
  1315. configurable: true
  1316. });
  1317. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1318. get: function () {
  1319. return PointerEventTypes._POINTERPICK;
  1320. },
  1321. enumerable: true,
  1322. configurable: true
  1323. });
  1324. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1325. get: function () {
  1326. return PointerEventTypes._POINTERTAP;
  1327. },
  1328. enumerable: true,
  1329. configurable: true
  1330. });
  1331. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1332. get: function () {
  1333. return PointerEventTypes._POINTERDOUBLETAP;
  1334. },
  1335. enumerable: true,
  1336. configurable: true
  1337. });
  1338. PointerEventTypes._POINTERDOWN = 0x01;
  1339. PointerEventTypes._POINTERUP = 0x02;
  1340. PointerEventTypes._POINTERMOVE = 0x04;
  1341. PointerEventTypes._POINTERWHEEL = 0x08;
  1342. PointerEventTypes._POINTERPICK = 0x10;
  1343. PointerEventTypes._POINTERTAP = 0x20;
  1344. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1345. return PointerEventTypes;
  1346. }());
  1347. BABYLON.PointerEventTypes = PointerEventTypes;
  1348. var PointerInfoBase = /** @class */ (function () {
  1349. function PointerInfoBase(type, event) {
  1350. this.type = type;
  1351. this.event = event;
  1352. }
  1353. return PointerInfoBase;
  1354. }());
  1355. BABYLON.PointerInfoBase = PointerInfoBase;
  1356. /**
  1357. * This class is used to store pointer related info for the onPrePointerObservable event.
  1358. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1359. */
  1360. var PointerInfoPre = /** @class */ (function (_super) {
  1361. __extends(PointerInfoPre, _super);
  1362. function PointerInfoPre(type, event, localX, localY) {
  1363. var _this = _super.call(this, type, event) || this;
  1364. _this.skipOnPointerObservable = false;
  1365. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1366. return _this;
  1367. }
  1368. return PointerInfoPre;
  1369. }(PointerInfoBase));
  1370. BABYLON.PointerInfoPre = PointerInfoPre;
  1371. /**
  1372. * This type contains all the data related to a pointer event in Babylon.js.
  1373. * 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.
  1374. */
  1375. var PointerInfo = /** @class */ (function (_super) {
  1376. __extends(PointerInfo, _super);
  1377. function PointerInfo(type, event, pickInfo) {
  1378. var _this = _super.call(this, type, event) || this;
  1379. _this.pickInfo = pickInfo;
  1380. return _this;
  1381. }
  1382. return PointerInfo;
  1383. }(PointerInfoBase));
  1384. BABYLON.PointerInfo = PointerInfo;
  1385. })(BABYLON || (BABYLON = {}));
  1386. //# sourceMappingURL=babylon.pointerEvents.js.map
  1387. "use strict";
  1388. var BABYLON;
  1389. (function (BABYLON) {
  1390. BABYLON.ToGammaSpace = 1 / 2.2;
  1391. BABYLON.ToLinearSpace = 2.2;
  1392. BABYLON.Epsilon = 0.001;
  1393. /**
  1394. * Class used to hold a RBG color
  1395. */
  1396. var Color3 = /** @class */ (function () {
  1397. /**
  1398. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1399. * @param r defines the red component (between 0 and 1, default is 0)
  1400. * @param g defines the green component (between 0 and 1, default is 0)
  1401. * @param b defines the blue component (between 0 and 1, default is 0)
  1402. */
  1403. function Color3(
  1404. /**
  1405. * Defines the red component (between 0 and 1, default is 0)
  1406. */
  1407. r,
  1408. /**
  1409. * Defines the green component (between 0 and 1, default is 0)
  1410. */
  1411. g,
  1412. /**
  1413. * Defines the blue component (between 0 and 1, default is 0)
  1414. */
  1415. b) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. this.r = r;
  1420. this.g = g;
  1421. this.b = b;
  1422. }
  1423. /**
  1424. * Creates a string with the Color3 current values
  1425. * @returns the string representation of the Color3 object
  1426. */
  1427. Color3.prototype.toString = function () {
  1428. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1429. };
  1430. /**
  1431. * Returns the string "Color3"
  1432. * @returns "Color3"
  1433. */
  1434. Color3.prototype.getClassName = function () {
  1435. return "Color3";
  1436. };
  1437. /**
  1438. * Compute the Color3 hash code
  1439. * @returns an unique number that can be used to hash Color3 objects
  1440. */
  1441. Color3.prototype.getHashCode = function () {
  1442. var hash = this.r || 0;
  1443. hash = (hash * 397) ^ (this.g || 0);
  1444. hash = (hash * 397) ^ (this.b || 0);
  1445. return hash;
  1446. };
  1447. // Operators
  1448. /**
  1449. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1450. * @param array defines the array where to store the r,g,b components
  1451. * @param index defines an optional index in the target array to define where to start storing values
  1452. * @returns the current Color3 object
  1453. */
  1454. Color3.prototype.toArray = function (array, index) {
  1455. if (index === undefined) {
  1456. index = 0;
  1457. }
  1458. array[index] = this.r;
  1459. array[index + 1] = this.g;
  1460. array[index + 2] = this.b;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1465. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1466. * @returns a new {BABYLON.Color4} object
  1467. */
  1468. Color3.prototype.toColor4 = function (alpha) {
  1469. if (alpha === void 0) { alpha = 1; }
  1470. return new Color4(this.r, this.g, this.b, alpha);
  1471. };
  1472. /**
  1473. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1474. * @returns the new array
  1475. */
  1476. Color3.prototype.asArray = function () {
  1477. var result = new Array();
  1478. this.toArray(result, 0);
  1479. return result;
  1480. };
  1481. /**
  1482. * Returns the luminance value
  1483. * @returns a float value
  1484. */
  1485. Color3.prototype.toLuminance = function () {
  1486. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1487. };
  1488. /**
  1489. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1490. * @param otherColor defines the second operand
  1491. * @returns the new Color3 object
  1492. */
  1493. Color3.prototype.multiply = function (otherColor) {
  1494. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1495. };
  1496. /**
  1497. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1498. * @param otherColor defines the second operand
  1499. * @param result defines the Color3 object where to store the result
  1500. * @returns the current Color3
  1501. */
  1502. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1503. result.r = this.r * otherColor.r;
  1504. result.g = this.g * otherColor.g;
  1505. result.b = this.b * otherColor.b;
  1506. return this;
  1507. };
  1508. /**
  1509. * Determines equality between Color3 objects
  1510. * @param otherColor defines the second operand
  1511. * @returns true if the rgb values are equal to the passed ones
  1512. */
  1513. Color3.prototype.equals = function (otherColor) {
  1514. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1515. };
  1516. /**
  1517. * Determines equality between the current Color3 object and a set of r,b,g values
  1518. * @param r defines the red component to check
  1519. * @param g defines the green component to check
  1520. * @param b defines the blue component to check
  1521. * @returns true if the rgb values are equal to the passed ones
  1522. */
  1523. Color3.prototype.equalsFloats = function (r, g, b) {
  1524. return this.r === r && this.g === g && this.b === b;
  1525. };
  1526. /**
  1527. * Multiplies in place each rgb value by scale
  1528. * @param scale defines the scaling factor
  1529. * @returns the updated Color3
  1530. */
  1531. Color3.prototype.scale = function (scale) {
  1532. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1533. };
  1534. /**
  1535. * Multiplies the rgb values by scale and stores the result into "result"
  1536. * @param scale defines the scaling factor
  1537. * @param result defines the Color3 object where to store the result
  1538. * @returns the unmodified current Color3
  1539. */
  1540. Color3.prototype.scaleToRef = function (scale, result) {
  1541. result.r = this.r * scale;
  1542. result.g = this.g * scale;
  1543. result.b = this.b * scale;
  1544. return this;
  1545. };
  1546. /**
  1547. * Scale the current Color3 values by a factor and add the result to a given Color3
  1548. * @param scale defines the scale factor
  1549. * @param result defines color to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1553. result.r += this.r * scale;
  1554. result.g += this.g * scale;
  1555. result.b += this.b * scale;
  1556. return this;
  1557. };
  1558. /**
  1559. * Clamps the rgb values by the min and max values and stores the result into "result"
  1560. * @param min defines minimum clamping value (default is 0)
  1561. * @param max defines maximum clamping value (default is 1)
  1562. * @param result defines color to store the result into
  1563. * @returns the original Color3
  1564. */
  1565. Color3.prototype.clampToRef = function (min, max, result) {
  1566. if (min === void 0) { min = 0; }
  1567. if (max === void 0) { max = 1; }
  1568. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1569. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1570. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1571. return this;
  1572. };
  1573. /**
  1574. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.add = function (otherColor) {
  1579. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.addToRef = function (otherColor, result) {
  1588. result.r = this.r + otherColor.r;
  1589. result.g = this.g + otherColor.g;
  1590. result.b = this.b + otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1595. * @param otherColor defines the second operand
  1596. * @returns the new Color3
  1597. */
  1598. Color3.prototype.subtract = function (otherColor) {
  1599. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1600. };
  1601. /**
  1602. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1603. * @param otherColor defines the second operand
  1604. * @param result defines Color3 object to store the result into
  1605. * @returns the unmodified current Color3
  1606. */
  1607. Color3.prototype.subtractToRef = function (otherColor, result) {
  1608. result.r = this.r - otherColor.r;
  1609. result.g = this.g - otherColor.g;
  1610. result.b = this.b - otherColor.b;
  1611. return this;
  1612. };
  1613. /**
  1614. * Copy the current object
  1615. * @returns a new Color3 copied the current one
  1616. */
  1617. Color3.prototype.clone = function () {
  1618. return new Color3(this.r, this.g, this.b);
  1619. };
  1620. /**
  1621. * Copies the rgb values from the source in the current Color3
  1622. * @param source defines the source Color3 object
  1623. * @returns the updated Color3 object
  1624. */
  1625. Color3.prototype.copyFrom = function (source) {
  1626. this.r = source.r;
  1627. this.g = source.g;
  1628. this.b = source.b;
  1629. return this;
  1630. };
  1631. /**
  1632. * Updates the Color3 rgb values from the passed floats
  1633. * @param r defines the red component to read from
  1634. * @param g defines the green component to read from
  1635. * @param b defines the blue component to read from
  1636. * @returns the current Color3 object
  1637. */
  1638. Color3.prototype.copyFromFloats = function (r, g, b) {
  1639. this.r = r;
  1640. this.g = g;
  1641. this.b = b;
  1642. return this;
  1643. };
  1644. /**
  1645. * Updates the Color3 rgb values from the passed floats
  1646. * @param r defines the red component to read from
  1647. * @param g defines the green component to read from
  1648. * @param b defines the blue component to read from
  1649. * @returns the current Color3 object
  1650. */
  1651. Color3.prototype.set = function (r, g, b) {
  1652. return this.copyFromFloats(r, g, b);
  1653. };
  1654. /**
  1655. * Compute the Color3 hexadecimal code as a string
  1656. * @returns a string containing the hexadecimal representation of the Color3 object
  1657. */
  1658. Color3.prototype.toHexString = function () {
  1659. var intR = (this.r * 255) | 0;
  1660. var intG = (this.g * 255) | 0;
  1661. var intB = (this.b * 255) | 0;
  1662. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to linear space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toLinearSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toLinearSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the linear space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1682. return this;
  1683. };
  1684. /**
  1685. * Computes a new Color3 converted from the current one to gamma space
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.prototype.toGammaSpace = function () {
  1689. var convertedColor = new Color3();
  1690. this.toGammaSpaceToRef(convertedColor);
  1691. return convertedColor;
  1692. };
  1693. /**
  1694. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1695. * @param convertedColor defines the Color3 object where to store the gamma space version
  1696. * @returns the unmodified Color3
  1697. */
  1698. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1699. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1700. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1701. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1702. return this;
  1703. };
  1704. // Statics
  1705. /**
  1706. * Creates a new Color3 from the string containing valid hexadecimal values
  1707. * @param hex defines a string containing valid hexadecimal values
  1708. * @returns a new Color3 object
  1709. */
  1710. Color3.FromHexString = function (hex) {
  1711. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1712. return new Color3(0, 0, 0);
  1713. }
  1714. var r = parseInt(hex.substring(1, 3), 16);
  1715. var g = parseInt(hex.substring(3, 5), 16);
  1716. var b = parseInt(hex.substring(5, 7), 16);
  1717. return Color3.FromInts(r, g, b);
  1718. };
  1719. /**
  1720. * Creates a new Vector3 from the starting index of the passed array
  1721. * @param array defines the source array
  1722. * @param offset defines an offset in the source array
  1723. * @returns a new Color3 object
  1724. */
  1725. Color3.FromArray = function (array, offset) {
  1726. if (offset === void 0) { offset = 0; }
  1727. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1728. };
  1729. /**
  1730. * Creates a new Color3 from integer values (< 256)
  1731. * @param r defines the red component to read from (value between 0 and 255)
  1732. * @param g defines the green component to read from (value between 0 and 255)
  1733. * @param b defines the blue component to read from (value between 0 and 255)
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.FromInts = function (r, g, b) {
  1737. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1738. };
  1739. /**
  1740. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1741. * @param start defines the start Color3 value
  1742. * @param end defines the end Color3 value
  1743. * @param amount defines the gradient value between start and end
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Lerp = function (start, end, amount) {
  1747. var r = start.r + ((end.r - start.r) * amount);
  1748. var g = start.g + ((end.g - start.g) * amount);
  1749. var b = start.b + ((end.b - start.b) * amount);
  1750. return new Color3(r, g, b);
  1751. };
  1752. /**
  1753. * Returns a Color3 value containing a red color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.Red = function () { return new Color3(1, 0, 0); };
  1757. /**
  1758. * Returns a Color3 value containing a green color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Green = function () { return new Color3(0, 1, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a blue color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a black color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Black = function () { return new Color3(0, 0, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a white color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.White = function () { return new Color3(1, 1, 1); };
  1777. /**
  1778. * Returns a Color3 value containing a purple color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1782. /**
  1783. * Returns a Color3 value containing a magenta color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1787. /**
  1788. * Returns a Color3 value containing a yellow color
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1792. /**
  1793. * Returns a Color3 value containing a gray color
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1797. /**
  1798. * Returns a Color3 value containing a teal color
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1802. /**
  1803. * Returns a Color3 value containing a random color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1807. return Color3;
  1808. }());
  1809. BABYLON.Color3 = Color3;
  1810. /**
  1811. * Class used to hold a RBGA color
  1812. */
  1813. var Color4 = /** @class */ (function () {
  1814. /**
  1815. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1816. * @param r defines the red component (between 0 and 1, default is 0)
  1817. * @param g defines the green component (between 0 and 1, default is 0)
  1818. * @param b defines the blue component (between 0 and 1, default is 0)
  1819. * @param a defines the alpha component (between 0 and 1, default is 1)
  1820. */
  1821. function Color4(
  1822. /**
  1823. * Defines the red component (between 0 and 1, default is 0)
  1824. */
  1825. r,
  1826. /**
  1827. * Defines the green component (between 0 and 1, default is 0)
  1828. */
  1829. g,
  1830. /**
  1831. * Defines the blue component (between 0 and 1, default is 0)
  1832. */
  1833. b,
  1834. /**
  1835. * Defines the alpha component (between 0 and 1, default is 1)
  1836. */
  1837. a) {
  1838. if (r === void 0) { r = 0; }
  1839. if (g === void 0) { g = 0; }
  1840. if (b === void 0) { b = 0; }
  1841. if (a === void 0) { a = 1; }
  1842. this.r = r;
  1843. this.g = g;
  1844. this.b = b;
  1845. this.a = a;
  1846. }
  1847. // Operators
  1848. /**
  1849. * Adds in place the passed Color4 values to the current Color4 object
  1850. * @param right defines the second operand
  1851. * @returns the current updated Color4 object
  1852. */
  1853. Color4.prototype.addInPlace = function (right) {
  1854. this.r += right.r;
  1855. this.g += right.g;
  1856. this.b += right.b;
  1857. this.a += right.a;
  1858. return this;
  1859. };
  1860. /**
  1861. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1862. * @returns the new array
  1863. */
  1864. Color4.prototype.asArray = function () {
  1865. var result = new Array();
  1866. this.toArray(result, 0);
  1867. return result;
  1868. };
  1869. /**
  1870. * Stores from the starting index in the passed array the Color4 successive values
  1871. * @param array defines the array where to store the r,g,b components
  1872. * @param index defines an optional index in the target array to define where to start storing values
  1873. * @returns the current Color4 object
  1874. */
  1875. Color4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.r;
  1880. array[index + 1] = this.g;
  1881. array[index + 2] = this.b;
  1882. array[index + 3] = this.a;
  1883. return this;
  1884. };
  1885. /**
  1886. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1887. * @param right defines the second operand
  1888. * @returns a new Color4 object
  1889. */
  1890. Color4.prototype.add = function (right) {
  1891. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1892. };
  1893. /**
  1894. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1895. * @param right defines the second operand
  1896. * @returns a new Color4 object
  1897. */
  1898. Color4.prototype.subtract = function (right) {
  1899. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1900. };
  1901. /**
  1902. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1903. * @param right defines the second operand
  1904. * @param result defines the Color4 object where to store the result
  1905. * @returns the current Color4 object
  1906. */
  1907. Color4.prototype.subtractToRef = function (right, result) {
  1908. result.r = this.r - right.r;
  1909. result.g = this.g - right.g;
  1910. result.b = this.b - right.b;
  1911. result.a = this.a - right.a;
  1912. return this;
  1913. };
  1914. /**
  1915. * Creates a new Color4 with the current Color4 values multiplied by scale
  1916. * @param scale defines the scaling factor to apply
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.scale = function (scale) {
  1920. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1921. };
  1922. /**
  1923. * Multiplies the current Color4 values by scale and stores the result in "result"
  1924. * @param scale defines the scaling factor to apply
  1925. * @param result defines the Color4 object where to store the result
  1926. * @returns the current unmodified Color4
  1927. */
  1928. Color4.prototype.scaleToRef = function (scale, result) {
  1929. result.r = this.r * scale;
  1930. result.g = this.g * scale;
  1931. result.b = this.b * scale;
  1932. result.a = this.a * scale;
  1933. return this;
  1934. };
  1935. /**
  1936. * Scale the current Color4 values by a factor and add the result to a given Color4
  1937. * @param scale defines the scale factor
  1938. * @param result defines the Color4 object where to store the result
  1939. * @returns the unmodified current Color4
  1940. */
  1941. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1942. result.r += this.r * scale;
  1943. result.g += this.g * scale;
  1944. result.b += this.b * scale;
  1945. result.a += this.a * scale;
  1946. return this;
  1947. };
  1948. /**
  1949. * Clamps the rgb values by the min and max values and stores the result into "result"
  1950. * @param min defines minimum clamping value (default is 0)
  1951. * @param max defines maximum clamping value (default is 1)
  1952. * @param result defines color to store the result into.
  1953. * @returns the cuurent Color4
  1954. */
  1955. Color4.prototype.clampToRef = function (min, max, result) {
  1956. if (min === void 0) { min = 0; }
  1957. if (max === void 0) { max = 1; }
  1958. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1959. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1960. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1961. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1962. return this;
  1963. };
  1964. /**
  1965. * Multipy an Color4 value by another and return a new Color4 object
  1966. * @param color defines the Color4 value to multiply by
  1967. * @returns a new Color4 object
  1968. */
  1969. Color4.prototype.multiply = function (color) {
  1970. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1971. };
  1972. /**
  1973. * Multipy a Color4 value by another and push the result in a reference value
  1974. * @param color defines the Color4 value to multiply by
  1975. * @param result defines the Color4 to fill the result in
  1976. * @returns the result Color4
  1977. */
  1978. Color4.prototype.multiplyToRef = function (color, result) {
  1979. result.r = this.r * color.r;
  1980. result.g = this.g * color.g;
  1981. result.b = this.b * color.b;
  1982. result.a = this.a * color.a;
  1983. return result;
  1984. };
  1985. /**
  1986. * Creates a string with the Color4 current values
  1987. * @returns the string representation of the Color4 object
  1988. */
  1989. Color4.prototype.toString = function () {
  1990. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1991. };
  1992. /**
  1993. * Returns the string "Color4"
  1994. * @returns "Color4"
  1995. */
  1996. Color4.prototype.getClassName = function () {
  1997. return "Color4";
  1998. };
  1999. /**
  2000. * Compute the Color4 hash code
  2001. * @returns an unique number that can be used to hash Color4 objects
  2002. */
  2003. Color4.prototype.getHashCode = function () {
  2004. var hash = this.r || 0;
  2005. hash = (hash * 397) ^ (this.g || 0);
  2006. hash = (hash * 397) ^ (this.b || 0);
  2007. hash = (hash * 397) ^ (this.a || 0);
  2008. return hash;
  2009. };
  2010. /**
  2011. * Creates a new Color4 copied from the current one
  2012. * @returns a new Color4 object
  2013. */
  2014. Color4.prototype.clone = function () {
  2015. return new Color4(this.r, this.g, this.b, this.a);
  2016. };
  2017. /**
  2018. * Copies the passed Color4 values into the current one
  2019. * @param source defines the source Color4 object
  2020. * @returns the current updated Color4 object
  2021. */
  2022. Color4.prototype.copyFrom = function (source) {
  2023. this.r = source.r;
  2024. this.g = source.g;
  2025. this.b = source.b;
  2026. this.a = source.a;
  2027. return this;
  2028. };
  2029. /**
  2030. * Copies the passed float values into the current one
  2031. * @param r defines the red component to read from
  2032. * @param g defines the green component to read from
  2033. * @param b defines the blue component to read from
  2034. * @param a defines the alpha component to read from
  2035. * @returns the current updated Color4 object
  2036. */
  2037. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2038. this.r = r;
  2039. this.g = g;
  2040. this.b = b;
  2041. this.a = a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Copies the passed float values into the current one
  2046. * @param r defines the red component to read from
  2047. * @param g defines the green component to read from
  2048. * @param b defines the blue component to read from
  2049. * @param a defines the alpha component to read from
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.set = function (r, g, b, a) {
  2053. return this.copyFromFloats(r, g, b, a);
  2054. };
  2055. /**
  2056. * Compute the Color4 hexadecimal code as a string
  2057. * @returns a string containing the hexadecimal representation of the Color4 object
  2058. */
  2059. Color4.prototype.toHexString = function () {
  2060. var intR = (this.r * 255) | 0;
  2061. var intG = (this.g * 255) | 0;
  2062. var intB = (this.b * 255) | 0;
  2063. var intA = (this.a * 255) | 0;
  2064. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2065. };
  2066. /**
  2067. * Computes a new Color4 converted from the current one to linear space
  2068. * @returns a new Color4 object
  2069. */
  2070. Color4.prototype.toLinearSpace = function () {
  2071. var convertedColor = new Color4();
  2072. this.toLinearSpaceToRef(convertedColor);
  2073. return convertedColor;
  2074. };
  2075. /**
  2076. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2077. * @param convertedColor defines the Color4 object where to store the linear space version
  2078. * @returns the unmodified Color4
  2079. */
  2080. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2081. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2082. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2083. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2084. convertedColor.a = this.a;
  2085. return this;
  2086. };
  2087. /**
  2088. * Computes a new Color4 converted from the current one to gamma space
  2089. * @returns a new Color4 object
  2090. */
  2091. Color4.prototype.toGammaSpace = function () {
  2092. var convertedColor = new Color4();
  2093. this.toGammaSpaceToRef(convertedColor);
  2094. return convertedColor;
  2095. };
  2096. /**
  2097. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2098. * @param convertedColor defines the Color4 object where to store the gamma space version
  2099. * @returns the unmodified Color4
  2100. */
  2101. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2102. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2103. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2104. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2105. convertedColor.a = this.a;
  2106. return this;
  2107. };
  2108. // Statics
  2109. /**
  2110. * Creates a new Color4 from the string containing valid hexadecimal values
  2111. * @param hex defines a string containing valid hexadecimal values
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.FromHexString = function (hex) {
  2115. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2116. return new Color4(0.0, 0.0, 0.0, 0.0);
  2117. }
  2118. var r = parseInt(hex.substring(1, 3), 16);
  2119. var g = parseInt(hex.substring(3, 5), 16);
  2120. var b = parseInt(hex.substring(5, 7), 16);
  2121. var a = parseInt(hex.substring(7, 9), 16);
  2122. return Color4.FromInts(r, g, b, a);
  2123. };
  2124. /**
  2125. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2126. * @param left defines the start value
  2127. * @param right defines the end value
  2128. * @param amount defines the gradient factor
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.Lerp = function (left, right, amount) {
  2132. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2133. Color4.LerpToRef(left, right, amount, result);
  2134. return result;
  2135. };
  2136. /**
  2137. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2138. * @param left defines the start value
  2139. * @param right defines the end value
  2140. * @param amount defines the gradient factor
  2141. * @param result defines the Color4 object where to store data
  2142. */
  2143. Color4.LerpToRef = function (left, right, amount, result) {
  2144. result.r = left.r + (right.r - left.r) * amount;
  2145. result.g = left.g + (right.g - left.g) * amount;
  2146. result.b = left.b + (right.b - left.b) * amount;
  2147. result.a = left.a + (right.a - left.a) * amount;
  2148. };
  2149. /**
  2150. * Creates a new Color4 from the starting index element of the passed array
  2151. * @param array defines the source array to read from
  2152. * @param offset defines the offset in the source array
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.FromArray = function (array, offset) {
  2156. if (offset === void 0) { offset = 0; }
  2157. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2158. };
  2159. /**
  2160. * Creates a new Color3 from integer values (< 256)
  2161. * @param r defines the red component to read from (value between 0 and 255)
  2162. * @param g defines the green component to read from (value between 0 and 255)
  2163. * @param b defines the blue component to read from (value between 0 and 255)
  2164. * @param a defines the alpha component to read from (value between 0 and 255)
  2165. * @returns a new Color3 object
  2166. */
  2167. Color4.FromInts = function (r, g, b, a) {
  2168. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2169. };
  2170. /**
  2171. * Check the content of a given array and convert it to an array containing RGBA data
  2172. * If the original array was already containing count * 4 values then it is returned directly
  2173. * @param colors defines the array to check
  2174. * @param count defines the number of RGBA data to expect
  2175. * @returns an array containing count * 4 values (RGBA)
  2176. */
  2177. Color4.CheckColors4 = function (colors, count) {
  2178. // Check if color3 was used
  2179. if (colors.length === count * 3) {
  2180. var colors4 = [];
  2181. for (var index = 0; index < colors.length; index += 3) {
  2182. var newIndex = (index / 3) * 4;
  2183. colors4[newIndex] = colors[index];
  2184. colors4[newIndex + 1] = colors[index + 1];
  2185. colors4[newIndex + 2] = colors[index + 2];
  2186. colors4[newIndex + 3] = 1.0;
  2187. }
  2188. return colors4;
  2189. }
  2190. return colors;
  2191. };
  2192. return Color4;
  2193. }());
  2194. BABYLON.Color4 = Color4;
  2195. var Vector2 = /** @class */ (function () {
  2196. /**
  2197. * Creates a new Vector2 from the passed x and y coordinates.
  2198. */
  2199. function Vector2(x, y) {
  2200. this.x = x;
  2201. this.y = y;
  2202. }
  2203. /**
  2204. * Returns a string with the Vector2 coordinates.
  2205. */
  2206. Vector2.prototype.toString = function () {
  2207. return "{X: " + this.x + " Y:" + this.y + "}";
  2208. };
  2209. /**
  2210. * Returns the string "Vector2"
  2211. */
  2212. Vector2.prototype.getClassName = function () {
  2213. return "Vector2";
  2214. };
  2215. /**
  2216. * Returns the Vector2 hash code as a number.
  2217. */
  2218. Vector2.prototype.getHashCode = function () {
  2219. var hash = this.x || 0;
  2220. hash = (hash * 397) ^ (this.y || 0);
  2221. return hash;
  2222. };
  2223. // Operators
  2224. /**
  2225. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2226. * Returns the Vector2.
  2227. */
  2228. Vector2.prototype.toArray = function (array, index) {
  2229. if (index === void 0) { index = 0; }
  2230. array[index] = this.x;
  2231. array[index + 1] = this.y;
  2232. return this;
  2233. };
  2234. /**
  2235. * Returns a new array with 2 elements : the Vector2 coordinates.
  2236. */
  2237. Vector2.prototype.asArray = function () {
  2238. var result = new Array();
  2239. this.toArray(result, 0);
  2240. return result;
  2241. };
  2242. /**
  2243. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2244. * Returns the updated Vector2.
  2245. */
  2246. Vector2.prototype.copyFrom = function (source) {
  2247. this.x = source.x;
  2248. this.y = source.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Sets the Vector2 coordinates with the passed floats.
  2253. * Returns the updated Vector2.
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the passed floats.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.set = function (x, y) {
  2265. return this.copyFromFloats(x, y);
  2266. };
  2267. /**
  2268. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2269. */
  2270. Vector2.prototype.add = function (otherVector) {
  2271. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2272. };
  2273. /**
  2274. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2275. * Returns the Vector2.
  2276. */
  2277. Vector2.prototype.addToRef = function (otherVector, result) {
  2278. result.x = this.x + otherVector.x;
  2279. result.y = this.y + otherVector.y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2284. * Returns the updated Vector2.
  2285. */
  2286. Vector2.prototype.addInPlace = function (otherVector) {
  2287. this.x += otherVector.x;
  2288. this.y += otherVector.y;
  2289. return this;
  2290. };
  2291. /**
  2292. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2293. */
  2294. Vector2.prototype.addVector3 = function (otherVector) {
  2295. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2296. };
  2297. /**
  2298. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2299. */
  2300. Vector2.prototype.subtract = function (otherVector) {
  2301. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2305. * Returns the Vector2.
  2306. */
  2307. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2308. result.x = this.x - otherVector.x;
  2309. result.y = this.y - otherVector.y;
  2310. return this;
  2311. };
  2312. /**
  2313. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2314. * Returns the updated Vector2.
  2315. */
  2316. Vector2.prototype.subtractInPlace = function (otherVector) {
  2317. this.x -= otherVector.x;
  2318. this.y -= otherVector.y;
  2319. return this;
  2320. };
  2321. /**
  2322. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2323. * Returns the updated Vector2.
  2324. */
  2325. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2326. this.x *= otherVector.x;
  2327. this.y *= otherVector.y;
  2328. return this;
  2329. };
  2330. /**
  2331. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2332. */
  2333. Vector2.prototype.multiply = function (otherVector) {
  2334. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2335. };
  2336. /**
  2337. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2338. * Returns the Vector2.
  2339. */
  2340. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2341. result.x = this.x * otherVector.x;
  2342. result.y = this.y * otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2347. */
  2348. Vector2.prototype.multiplyByFloats = function (x, y) {
  2349. return new Vector2(this.x * x, this.y * y);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2353. */
  2354. Vector2.prototype.divide = function (otherVector) {
  2355. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2356. };
  2357. /**
  2358. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2359. * Returns the Vector2.
  2360. */
  2361. Vector2.prototype.divideToRef = function (otherVector, result) {
  2362. result.x = this.x / otherVector.x;
  2363. result.y = this.y / otherVector.y;
  2364. return this;
  2365. };
  2366. /**
  2367. * Divides the current Vector3 coordinates by the passed ones.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector2.prototype.divideInPlace = function (otherVector) {
  2371. return this.divideToRef(otherVector, this);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 with current Vector2 negated coordinates.
  2375. */
  2376. Vector2.prototype.negate = function () {
  2377. return new Vector2(-this.x, -this.y);
  2378. };
  2379. /**
  2380. * Multiply the Vector2 coordinates by scale.
  2381. * Returns the updated Vector2.
  2382. */
  2383. Vector2.prototype.scaleInPlace = function (scale) {
  2384. this.x *= scale;
  2385. this.y *= scale;
  2386. return this;
  2387. };
  2388. /**
  2389. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2390. */
  2391. Vector2.prototype.scale = function (scale) {
  2392. var result = new Vector2(0, 0);
  2393. this.scaleToRef(scale, result);
  2394. return result;
  2395. };
  2396. /**
  2397. * Scale the current Vector2 values by a factor to a given Vector2
  2398. * @param scale defines the scale factor
  2399. * @param result defines the Vector2 object where to store the result
  2400. * @returns the unmodified current Vector2
  2401. */
  2402. Vector2.prototype.scaleToRef = function (scale, result) {
  2403. result.x = this.x * scale;
  2404. result.y = this.y * scale;
  2405. return this;
  2406. };
  2407. /**
  2408. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2409. * @param scale defines the scale factor
  2410. * @param result defines the Vector2 object where to store the result
  2411. * @returns the unmodified current Vector2
  2412. */
  2413. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2414. result.x += this.x * scale;
  2415. result.y += this.y * scale;
  2416. return this;
  2417. };
  2418. /**
  2419. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2420. */
  2421. Vector2.prototype.equals = function (otherVector) {
  2422. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2423. };
  2424. /**
  2425. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2426. */
  2427. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2428. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2429. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2430. };
  2431. // Properties
  2432. /**
  2433. * Returns the vector length (float).
  2434. */
  2435. Vector2.prototype.length = function () {
  2436. return Math.sqrt(this.x * this.x + this.y * this.y);
  2437. };
  2438. /**
  2439. * Returns the vector squared length (float);
  2440. */
  2441. Vector2.prototype.lengthSquared = function () {
  2442. return (this.x * this.x + this.y * this.y);
  2443. };
  2444. // Methods
  2445. /**
  2446. * Normalize the vector.
  2447. * Returns the updated Vector2.
  2448. */
  2449. Vector2.prototype.normalize = function () {
  2450. var len = this.length();
  2451. if (len === 0)
  2452. return this;
  2453. var num = 1.0 / len;
  2454. this.x *= num;
  2455. this.y *= num;
  2456. return this;
  2457. };
  2458. /**
  2459. * Returns a new Vector2 copied from the Vector2.
  2460. */
  2461. Vector2.prototype.clone = function () {
  2462. return new Vector2(this.x, this.y);
  2463. };
  2464. // Statics
  2465. /**
  2466. * Returns a new Vector2(0, 0)
  2467. */
  2468. Vector2.Zero = function () {
  2469. return new Vector2(0, 0);
  2470. };
  2471. /**
  2472. * Returns a new Vector2(1, 1)
  2473. */
  2474. Vector2.One = function () {
  2475. return new Vector2(1, 1);
  2476. };
  2477. /**
  2478. * Returns a new Vector2 set from the passed index element of the passed array.
  2479. */
  2480. Vector2.FromArray = function (array, offset) {
  2481. if (offset === void 0) { offset = 0; }
  2482. return new Vector2(array[offset], array[offset + 1]);
  2483. };
  2484. /**
  2485. * Sets "result" from the passed index element of the passed array.
  2486. */
  2487. Vector2.FromArrayToRef = function (array, offset, result) {
  2488. result.x = array[offset];
  2489. result.y = array[offset + 1];
  2490. };
  2491. /**
  2492. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2493. */
  2494. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2495. var squared = amount * amount;
  2496. var cubed = amount * squared;
  2497. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2498. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2499. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2500. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2501. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2502. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2503. return new Vector2(x, y);
  2504. };
  2505. /**
  2506. * 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".
  2507. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2508. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2509. */
  2510. Vector2.Clamp = function (value, min, max) {
  2511. var x = value.x;
  2512. x = (x > max.x) ? max.x : x;
  2513. x = (x < min.x) ? min.x : x;
  2514. var y = value.y;
  2515. y = (y > max.y) ? max.y : y;
  2516. y = (y < min.y) ? min.y : y;
  2517. return new Vector2(x, y);
  2518. };
  2519. /**
  2520. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2521. */
  2522. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2523. var squared = amount * amount;
  2524. var cubed = amount * squared;
  2525. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2526. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2527. var part3 = (cubed - (2.0 * squared)) + amount;
  2528. var part4 = cubed - squared;
  2529. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2530. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2531. return new Vector2(x, y);
  2532. };
  2533. /**
  2534. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2535. */
  2536. Vector2.Lerp = function (start, end, amount) {
  2537. var x = start.x + ((end.x - start.x) * amount);
  2538. var y = start.y + ((end.y - start.y) * amount);
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns the dot product (float) of the vector "left" and the vector "right".
  2543. */
  2544. Vector2.Dot = function (left, right) {
  2545. return left.x * right.x + left.y * right.y;
  2546. };
  2547. /**
  2548. * Returns a new Vector2 equal to the normalized passed vector.
  2549. */
  2550. Vector2.Normalize = function (vector) {
  2551. var newVector = vector.clone();
  2552. newVector.normalize();
  2553. return newVector;
  2554. };
  2555. /**
  2556. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2557. */
  2558. Vector2.Minimize = function (left, right) {
  2559. var x = (left.x < right.x) ? left.x : right.x;
  2560. var y = (left.y < right.y) ? left.y : right.y;
  2561. return new Vector2(x, y);
  2562. };
  2563. /**
  2564. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2565. */
  2566. Vector2.Maximize = function (left, right) {
  2567. var x = (left.x > right.x) ? left.x : right.x;
  2568. var y = (left.y > right.y) ? left.y : right.y;
  2569. return new Vector2(x, y);
  2570. };
  2571. /**
  2572. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2573. */
  2574. Vector2.Transform = function (vector, transformation) {
  2575. var r = Vector2.Zero();
  2576. Vector2.TransformToRef(vector, transformation, r);
  2577. return r;
  2578. };
  2579. /**
  2580. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2581. */
  2582. Vector2.TransformToRef = function (vector, transformation, result) {
  2583. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2584. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2585. result.x = x;
  2586. result.y = y;
  2587. };
  2588. /**
  2589. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2590. */
  2591. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2592. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2593. var sign = a < 0 ? -1 : 1;
  2594. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2595. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2596. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2597. };
  2598. /**
  2599. * Returns the distance (float) between the vectors "value1" and "value2".
  2600. */
  2601. Vector2.Distance = function (value1, value2) {
  2602. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2603. };
  2604. /**
  2605. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2606. */
  2607. Vector2.DistanceSquared = function (value1, value2) {
  2608. var x = value1.x - value2.x;
  2609. var y = value1.y - value2.y;
  2610. return (x * x) + (y * y);
  2611. };
  2612. /**
  2613. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2614. */
  2615. Vector2.Center = function (value1, value2) {
  2616. var center = value1.add(value2);
  2617. center.scaleInPlace(0.5);
  2618. return center;
  2619. };
  2620. /**
  2621. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2622. */
  2623. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2624. var l2 = Vector2.DistanceSquared(segA, segB);
  2625. if (l2 === 0.0) {
  2626. return Vector2.Distance(p, segA);
  2627. }
  2628. var v = segB.subtract(segA);
  2629. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2630. var proj = segA.add(v.multiplyByFloats(t, t));
  2631. return Vector2.Distance(p, proj);
  2632. };
  2633. return Vector2;
  2634. }());
  2635. BABYLON.Vector2 = Vector2;
  2636. /**
  2637. * Classed used to store (x,y,z) vector representation
  2638. * A Vector3 is the main object used in 3D geometry
  2639. * It can represent etiher the coordinates of a point the space, either a direction
  2640. * Reminder: Babylon.js uses a left handed forward facing system
  2641. */
  2642. var Vector3 = /** @class */ (function () {
  2643. /**
  2644. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2645. * @param x defines the first coordinates (on X axis)
  2646. * @param y defines the second coordinates (on Y axis)
  2647. * @param z defines the third coordinates (on Z axis)
  2648. */
  2649. function Vector3(
  2650. /**
  2651. * Defines the first coordinates (on X axis)
  2652. */
  2653. x,
  2654. /**
  2655. * Defines the second coordinates (on Y axis)
  2656. */
  2657. y,
  2658. /**
  2659. * Defines the third coordinates (on Z axis)
  2660. */
  2661. z) {
  2662. this.x = x;
  2663. this.y = y;
  2664. this.z = z;
  2665. }
  2666. /**
  2667. * Creates a string representation of the Vector3
  2668. * @returns a string with the Vector3 coordinates.
  2669. */
  2670. Vector3.prototype.toString = function () {
  2671. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2672. };
  2673. /**
  2674. * Gets the class name
  2675. * @returns the string "Vector3"
  2676. */
  2677. Vector3.prototype.getClassName = function () {
  2678. return "Vector3";
  2679. };
  2680. /**
  2681. * Creates the Vector3 hash code
  2682. * @returns a number which tends to be unique between Vector3 instances
  2683. */
  2684. Vector3.prototype.getHashCode = function () {
  2685. var hash = this.x || 0;
  2686. hash = (hash * 397) ^ (this.y || 0);
  2687. hash = (hash * 397) ^ (this.z || 0);
  2688. return hash;
  2689. };
  2690. // Operators
  2691. /**
  2692. * Creates an array containing three elements : the coordinates of the Vector3
  2693. * @returns a new array of numbers
  2694. */
  2695. Vector3.prototype.asArray = function () {
  2696. var result = [];
  2697. this.toArray(result, 0);
  2698. return result;
  2699. };
  2700. /**
  2701. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2702. * @param array defines the destination array
  2703. * @param index defines the offset in the destination array
  2704. * @returns the current Vector3
  2705. */
  2706. Vector3.prototype.toArray = function (array, index) {
  2707. if (index === void 0) { index = 0; }
  2708. array[index] = this.x;
  2709. array[index + 1] = this.y;
  2710. array[index + 2] = this.z;
  2711. return this;
  2712. };
  2713. /**
  2714. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2715. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2716. */
  2717. Vector3.prototype.toQuaternion = function () {
  2718. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2719. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2720. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2721. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2722. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2723. var cosy = Math.cos(this.y * 0.5);
  2724. var siny = Math.sin(this.y * 0.5);
  2725. result.x = coszMinusx * siny;
  2726. result.y = -sinzMinusx * siny;
  2727. result.z = sinxPlusz * cosy;
  2728. result.w = cosxPlusz * cosy;
  2729. return result;
  2730. };
  2731. /**
  2732. * Adds the passed vector to the current Vector3
  2733. * @param otherVector defines the second operand
  2734. * @returns the current updated Vector3
  2735. */
  2736. Vector3.prototype.addInPlace = function (otherVector) {
  2737. this.x += otherVector.x;
  2738. this.y += otherVector.y;
  2739. this.z += otherVector.z;
  2740. return this;
  2741. };
  2742. /**
  2743. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2744. * @param otherVector defines the second operand
  2745. * @returns the resulting Vector3
  2746. */
  2747. Vector3.prototype.add = function (otherVector) {
  2748. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2749. };
  2750. /**
  2751. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2752. * @param otherVector defines the second operand
  2753. * @param result defines the Vector3 object where to store the result
  2754. * @returns the current Vector3
  2755. */
  2756. Vector3.prototype.addToRef = function (otherVector, result) {
  2757. result.x = this.x + otherVector.x;
  2758. result.y = this.y + otherVector.y;
  2759. result.z = this.z + otherVector.z;
  2760. return this;
  2761. };
  2762. /**
  2763. * Subtract the passed vector from the current Vector3
  2764. * @param otherVector defines the second operand
  2765. * @returns the current updated Vector3
  2766. */
  2767. Vector3.prototype.subtractInPlace = function (otherVector) {
  2768. this.x -= otherVector.x;
  2769. this.y -= otherVector.y;
  2770. this.z -= otherVector.z;
  2771. return this;
  2772. };
  2773. /**
  2774. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2775. * @param otherVector defines the second operand
  2776. * @returns the resulting Vector3
  2777. */
  2778. Vector3.prototype.subtract = function (otherVector) {
  2779. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2780. };
  2781. /**
  2782. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2783. * @param otherVector defines the second operand
  2784. * @param result defines the Vector3 object where to store the result
  2785. * @returns the current Vector3
  2786. */
  2787. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2788. result.x = this.x - otherVector.x;
  2789. result.y = this.y - otherVector.y;
  2790. result.z = this.z - otherVector.z;
  2791. return this;
  2792. };
  2793. /**
  2794. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2795. * @param x defines the x coordinate of the operand
  2796. * @param y defines the y coordinate of the operand
  2797. * @param z defines the z coordinate of the operand
  2798. * @returns the resulting Vector3
  2799. */
  2800. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2801. return new Vector3(this.x - x, this.y - y, this.z - z);
  2802. };
  2803. /**
  2804. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2805. * @param x defines the x coordinate of the operand
  2806. * @param y defines the y coordinate of the operand
  2807. * @param z defines the z coordinate of the operand
  2808. * @param result defines the Vector3 object where to store the result
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2812. result.x = this.x - x;
  2813. result.y = this.y - y;
  2814. result.z = this.z - z;
  2815. return this;
  2816. };
  2817. /**
  2818. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2819. * @returns a new Vector3
  2820. */
  2821. Vector3.prototype.negate = function () {
  2822. return new Vector3(-this.x, -this.y, -this.z);
  2823. };
  2824. /**
  2825. * Multiplies the Vector3 coordinates by the float "scale"
  2826. * @param scale defines the multiplier factor
  2827. * @returns the current updated Vector3
  2828. */
  2829. Vector3.prototype.scaleInPlace = function (scale) {
  2830. this.x *= scale;
  2831. this.y *= scale;
  2832. this.z *= scale;
  2833. return this;
  2834. };
  2835. /**
  2836. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2837. * @param scale defines the multiplier factor
  2838. * @returns a new Vector3
  2839. */
  2840. Vector3.prototype.scale = function (scale) {
  2841. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2842. };
  2843. /**
  2844. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2845. * @param scale defines the multiplier factor
  2846. * @param result defines the Vector3 object where to store the result
  2847. * @returns the current Vector3
  2848. */
  2849. Vector3.prototype.scaleToRef = function (scale, result) {
  2850. result.x = this.x * scale;
  2851. result.y = this.y * scale;
  2852. result.z = this.z * scale;
  2853. return this;
  2854. };
  2855. /**
  2856. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2857. * @param scale defines the scale factor
  2858. * @param result defines the Vector3 object where to store the result
  2859. * @returns the unmodified current Vector3
  2860. */
  2861. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2862. result.x += this.x * scale;
  2863. result.y += this.y * scale;
  2864. result.z += this.z * scale;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2869. * @param otherVector defines the second operand
  2870. * @returns true if both vectors are equals
  2871. */
  2872. Vector3.prototype.equals = function (otherVector) {
  2873. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2874. };
  2875. /**
  2876. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2877. * @param otherVector defines the second operand
  2878. * @param epsilon defines the minimal distance to define values as equals
  2879. * @returns true if both vectors are distant less than epsilon
  2880. */
  2881. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2882. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2883. 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);
  2884. };
  2885. /**
  2886. * Returns true if the current Vector3 coordinates equals the passed floats
  2887. * @param x defines the x coordinate of the operand
  2888. * @param y defines the y coordinate of the operand
  2889. * @param z defines the z coordinate of the operand
  2890. * @returns true if both vectors are equals
  2891. */
  2892. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2893. return this.x === x && this.y === y && this.z === z;
  2894. };
  2895. /**
  2896. * Multiplies the current Vector3 coordinates by the passed ones
  2897. * @param otherVector defines the second operand
  2898. * @returns the current updated Vector3
  2899. */
  2900. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2901. this.x *= otherVector.x;
  2902. this.y *= otherVector.y;
  2903. this.z *= otherVector.z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2908. * @param otherVector defines the second operand
  2909. * @returns the new Vector3
  2910. */
  2911. Vector3.prototype.multiply = function (otherVector) {
  2912. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2913. };
  2914. /**
  2915. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2916. * @param otherVector defines the second operand
  2917. * @param result defines the Vector3 object where to store the result
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2921. result.x = this.x * otherVector.x;
  2922. result.y = this.y * otherVector.y;
  2923. result.z = this.z * otherVector.z;
  2924. return this;
  2925. };
  2926. /**
  2927. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2928. * @param x defines the x coordinate of the operand
  2929. * @param y defines the y coordinate of the operand
  2930. * @param z defines the z coordinate of the operand
  2931. * @returns the new Vector3
  2932. */
  2933. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2934. return new Vector3(this.x * x, this.y * y, this.z * z);
  2935. };
  2936. /**
  2937. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2938. * @param otherVector defines the second operand
  2939. * @returns the new Vector3
  2940. */
  2941. Vector3.prototype.divide = function (otherVector) {
  2942. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2943. };
  2944. /**
  2945. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2946. * @param otherVector defines the second operand
  2947. * @param result defines the Vector3 object where to store the result
  2948. * @returns the current Vector3
  2949. */
  2950. Vector3.prototype.divideToRef = function (otherVector, result) {
  2951. result.x = this.x / otherVector.x;
  2952. result.y = this.y / otherVector.y;
  2953. result.z = this.z / otherVector.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Divides the current Vector3 coordinates by the passed ones.
  2958. * @param otherVector defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.divideInPlace = function (otherVector) {
  2962. return this.divideToRef(otherVector, this);
  2963. };
  2964. /**
  2965. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2966. * @param other defines the second operand
  2967. * @returns the current updated Vector3
  2968. */
  2969. Vector3.prototype.minimizeInPlace = function (other) {
  2970. if (other.x < this.x)
  2971. this.x = other.x;
  2972. if (other.y < this.y)
  2973. this.y = other.y;
  2974. if (other.z < this.z)
  2975. this.z = other.z;
  2976. return this;
  2977. };
  2978. /**
  2979. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2980. * @param other defines the second operand
  2981. * @returns the current updated Vector3
  2982. */
  2983. Vector3.prototype.maximizeInPlace = function (other) {
  2984. if (other.x > this.x)
  2985. this.x = other.x;
  2986. if (other.y > this.y)
  2987. this.y = other.y;
  2988. if (other.z > this.z)
  2989. this.z = other.z;
  2990. return this;
  2991. };
  2992. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2993. /**
  2994. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2995. */
  2996. get: function () {
  2997. var absX = Math.abs(this.x);
  2998. var absY = Math.abs(this.y);
  2999. if (absX !== absY) {
  3000. return true;
  3001. }
  3002. var absZ = Math.abs(this.z);
  3003. if (absX !== absZ) {
  3004. return true;
  3005. }
  3006. if (absY !== absZ) {
  3007. return true;
  3008. }
  3009. return false;
  3010. },
  3011. enumerable: true,
  3012. configurable: true
  3013. });
  3014. // Properties
  3015. /**
  3016. * Gets the length of the Vector3
  3017. * @returns the length of the Vecto3
  3018. */
  3019. Vector3.prototype.length = function () {
  3020. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3021. };
  3022. /**
  3023. * Gets the squared length of the Vector3
  3024. * @returns squared length of the Vector3
  3025. */
  3026. Vector3.prototype.lengthSquared = function () {
  3027. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3028. };
  3029. /**
  3030. * Normalize the current Vector3.
  3031. * Please note that this is an in place operation.
  3032. * @returns the current updated Vector3
  3033. */
  3034. Vector3.prototype.normalize = function () {
  3035. var len = this.length();
  3036. if (len === 0 || len === 1.0)
  3037. return this;
  3038. var num = 1.0 / len;
  3039. this.x *= num;
  3040. this.y *= num;
  3041. this.z *= num;
  3042. return this;
  3043. };
  3044. /**
  3045. * Normalize the current Vector3 to a new vector
  3046. * @returns the new Vector3
  3047. */
  3048. Vector3.prototype.normalizeToNew = function () {
  3049. var normalized = new Vector3(0, 0, 0);
  3050. this.normalizeToRef(normalized);
  3051. return normalized;
  3052. };
  3053. /**
  3054. * Normalize the current Vector3 to the reference
  3055. * @param reference define the Vector3 to update
  3056. * @returns the updated Vector3
  3057. */
  3058. Vector3.prototype.normalizeToRef = function (reference) {
  3059. var len = this.length();
  3060. if (len === 0 || len === 1.0) {
  3061. reference.set(this.x, this.y, this.z);
  3062. return reference;
  3063. }
  3064. var scale = 1.0 / len;
  3065. this.scaleToRef(scale, reference);
  3066. return reference;
  3067. };
  3068. /**
  3069. * Creates a new Vector3 copied from the current Vector3
  3070. * @returns the new Vector3
  3071. */
  3072. Vector3.prototype.clone = function () {
  3073. return new Vector3(this.x, this.y, this.z);
  3074. };
  3075. /**
  3076. * Copies the passed vector coordinates to the current Vector3 ones
  3077. * @param source defines the source Vector3
  3078. * @returns the current updated Vector3
  3079. */
  3080. Vector3.prototype.copyFrom = function (source) {
  3081. this.x = source.x;
  3082. this.y = source.y;
  3083. this.z = source.z;
  3084. return this;
  3085. };
  3086. /**
  3087. * Copies the passed floats to the current Vector3 coordinates
  3088. * @param x defines the x coordinate of the operand
  3089. * @param y defines the y coordinate of the operand
  3090. * @param z defines the z coordinate of the operand
  3091. * @returns the current updated Vector3
  3092. */
  3093. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3094. this.x = x;
  3095. this.y = y;
  3096. this.z = z;
  3097. return this;
  3098. };
  3099. /**
  3100. * Copies the passed floats to the current Vector3 coordinates
  3101. * @param x defines the x coordinate of the operand
  3102. * @param y defines the y coordinate of the operand
  3103. * @param z defines the z coordinate of the operand
  3104. * @returns the current updated Vector3
  3105. */
  3106. Vector3.prototype.set = function (x, y, z) {
  3107. return this.copyFromFloats(x, y, z);
  3108. };
  3109. // Statics
  3110. /**
  3111. * Get the clip factor between two vectors
  3112. * @param vector0 defines the first operand
  3113. * @param vector1 defines the second operand
  3114. * @param axis defines the axis to use
  3115. * @param size defines the size along the axis
  3116. * @returns the clip factor
  3117. */
  3118. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3119. var d0 = Vector3.Dot(vector0, axis) - size;
  3120. var d1 = Vector3.Dot(vector1, axis) - size;
  3121. var s = d0 / (d0 - d1);
  3122. return s;
  3123. };
  3124. /**
  3125. * Get angle between two vectors
  3126. * @param vector0 angle between vector0 and vector1
  3127. * @param vector1 angle between vector0 and vector1
  3128. * @param normal direction of the normal
  3129. * @return the angle between vector0 and vector1
  3130. */
  3131. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3132. var v0 = vector0.clone().normalize();
  3133. var v1 = vector1.clone().normalize();
  3134. var dot = Vector3.Dot(v0, v1);
  3135. var n = Vector3.Cross(v0, v1);
  3136. if (Vector3.Dot(n, normal) > 0) {
  3137. return Math.acos(dot);
  3138. }
  3139. return -Math.acos(dot);
  3140. };
  3141. /**
  3142. * Returns a new Vector3 set from the index "offset" of the passed array
  3143. * @param array defines the source array
  3144. * @param offset defines the offset in the source array
  3145. * @returns the new Vector3
  3146. */
  3147. Vector3.FromArray = function (array, offset) {
  3148. if (!offset) {
  3149. offset = 0;
  3150. }
  3151. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3152. };
  3153. /**
  3154. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3155. * This function is deprecated. Use FromArray instead
  3156. * @param array defines the source array
  3157. * @param offset defines the offset in the source array
  3158. * @returns the new Vector3
  3159. */
  3160. Vector3.FromFloatArray = function (array, offset) {
  3161. return Vector3.FromArray(array, offset);
  3162. };
  3163. /**
  3164. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3165. * @param array defines the source array
  3166. * @param offset defines the offset in the source array
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.FromArrayToRef = function (array, offset, result) {
  3170. result.x = array[offset];
  3171. result.y = array[offset + 1];
  3172. result.z = array[offset + 2];
  3173. };
  3174. /**
  3175. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3176. * This function is deprecated. Use FromArrayToRef instead.
  3177. * @param array defines the source array
  3178. * @param offset defines the offset in the source array
  3179. * @param result defines the Vector3 where to store the result
  3180. */
  3181. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3182. return Vector3.FromArrayToRef(array, offset, result);
  3183. };
  3184. /**
  3185. * Sets the passed vector "result" with the passed floats.
  3186. * @param x defines the x coordinate of the source
  3187. * @param y defines the y coordinate of the source
  3188. * @param z defines the z coordinate of the source
  3189. * @param result defines the Vector3 where to store the result
  3190. */
  3191. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3192. result.x = x;
  3193. result.y = y;
  3194. result.z = z;
  3195. };
  3196. /**
  3197. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3198. * @returns a new empty Vector3
  3199. */
  3200. Vector3.Zero = function () {
  3201. return new Vector3(0.0, 0.0, 0.0);
  3202. };
  3203. /**
  3204. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3205. * @returns a new unit Vector3
  3206. */
  3207. Vector3.One = function () {
  3208. return new Vector3(1.0, 1.0, 1.0);
  3209. };
  3210. /**
  3211. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3212. * @returns a new up Vector3
  3213. */
  3214. Vector3.Up = function () {
  3215. return new Vector3(0.0, 1.0, 0.0);
  3216. };
  3217. /**
  3218. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3219. * @returns a new forward Vector3
  3220. */
  3221. Vector3.Forward = function () {
  3222. return new Vector3(0.0, 0.0, 1.0);
  3223. };
  3224. /**
  3225. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3226. * @returns a new right Vector3
  3227. */
  3228. Vector3.Right = function () {
  3229. return new Vector3(1.0, 0.0, 0.0);
  3230. };
  3231. /**
  3232. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3233. * @returns a new left Vector3
  3234. */
  3235. Vector3.Left = function () {
  3236. return new Vector3(-1.0, 0.0, 0.0);
  3237. };
  3238. /**
  3239. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3240. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3241. * @param vector defines the Vector3 to transform
  3242. * @param transformation defines the transformation matrix
  3243. * @returns the transformed Vector3
  3244. */
  3245. Vector3.TransformCoordinates = function (vector, transformation) {
  3246. var result = Vector3.Zero();
  3247. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3252. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3253. * @param vector defines the Vector3 to transform
  3254. * @param transformation defines the transformation matrix
  3255. * @param result defines the Vector3 where to store the result
  3256. */
  3257. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3258. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3259. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3260. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3261. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3262. result.x = x / w;
  3263. result.y = y / w;
  3264. result.z = z / w;
  3265. };
  3266. /**
  3267. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3268. * This method computes tranformed coordinates only, not transformed direction vectors
  3269. * @param x define the x coordinate of the source vector
  3270. * @param y define the y coordinate of the source vector
  3271. * @param z define the z coordinate of the source vector
  3272. * @param transformation defines the transformation matrix
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3276. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3277. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3278. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3279. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3280. result.x = rx / rw;
  3281. result.y = ry / rw;
  3282. result.z = rz / rw;
  3283. };
  3284. /**
  3285. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3286. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3287. * @param vector defines the Vector3 to transform
  3288. * @param transformation defines the transformation matrix
  3289. * @returns the new Vector3
  3290. */
  3291. Vector3.TransformNormal = function (vector, transformation) {
  3292. var result = Vector3.Zero();
  3293. Vector3.TransformNormalToRef(vector, transformation, result);
  3294. return result;
  3295. };
  3296. /**
  3297. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3298. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3299. * @param vector defines the Vector3 to transform
  3300. * @param transformation defines the transformation matrix
  3301. * @param result defines the Vector3 where to store the result
  3302. */
  3303. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3304. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3305. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3306. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3307. result.x = x;
  3308. result.y = y;
  3309. result.z = z;
  3310. };
  3311. /**
  3312. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3313. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3314. * @param x define the x coordinate of the source vector
  3315. * @param y define the y coordinate of the source vector
  3316. * @param z define the z coordinate of the source vector
  3317. * @param transformation defines the transformation matrix
  3318. * @param result defines the Vector3 where to store the result
  3319. */
  3320. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3321. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3322. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3323. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3327. * @param value1 defines the first control point
  3328. * @param value2 defines the second control point
  3329. * @param value3 defines the third control point
  3330. * @param value4 defines the fourth control point
  3331. * @param amount defines the amount on the spline to use
  3332. * @returns the new Vector3
  3333. */
  3334. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3335. var squared = amount * amount;
  3336. var cubed = amount * squared;
  3337. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3338. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3339. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3340. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3341. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3342. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3343. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3344. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3345. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3346. return new Vector3(x, y, z);
  3347. };
  3348. /**
  3349. * 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"
  3350. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3351. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3352. * @param value defines the current value
  3353. * @param min defines the lower range value
  3354. * @param max defines the upper range value
  3355. * @returns the new Vector3
  3356. */
  3357. Vector3.Clamp = function (value, min, max) {
  3358. var x = value.x;
  3359. x = (x > max.x) ? max.x : x;
  3360. x = (x < min.x) ? min.x : x;
  3361. var y = value.y;
  3362. y = (y > max.y) ? max.y : y;
  3363. y = (y < min.y) ? min.y : y;
  3364. var z = value.z;
  3365. z = (z > max.z) ? max.z : z;
  3366. z = (z < min.z) ? min.z : z;
  3367. return new Vector3(x, y, z);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3371. * @param value1 defines the first control point
  3372. * @param tangent1 defines the first tangent vector
  3373. * @param value2 defines the second control point
  3374. * @param tangent2 defines the second tangent vector
  3375. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3376. * @returns the new Vector3
  3377. */
  3378. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3379. var squared = amount * amount;
  3380. var cubed = amount * squared;
  3381. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3382. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3383. var part3 = (cubed - (2.0 * squared)) + amount;
  3384. var part4 = cubed - squared;
  3385. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3386. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3387. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3388. return new Vector3(x, y, z);
  3389. };
  3390. /**
  3391. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3392. * @param start defines the start value
  3393. * @param end defines the end value
  3394. * @param amount max defines amount between both (between 0 and 1)
  3395. * @returns the new Vector3
  3396. */
  3397. Vector3.Lerp = function (start, end, amount) {
  3398. var result = new Vector3(0, 0, 0);
  3399. Vector3.LerpToRef(start, end, amount, result);
  3400. return result;
  3401. };
  3402. /**
  3403. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3404. * @param start defines the start value
  3405. * @param end defines the end value
  3406. * @param amount max defines amount between both (between 0 and 1)
  3407. * @param result defines the Vector3 where to store the result
  3408. */
  3409. Vector3.LerpToRef = function (start, end, amount, result) {
  3410. result.x = start.x + ((end.x - start.x) * amount);
  3411. result.y = start.y + ((end.y - start.y) * amount);
  3412. result.z = start.z + ((end.z - start.z) * amount);
  3413. };
  3414. /**
  3415. * Returns the dot product (float) between the vectors "left" and "right"
  3416. * @param left defines the left operand
  3417. * @param right defines the right operand
  3418. * @returns the dot product
  3419. */
  3420. Vector3.Dot = function (left, right) {
  3421. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3422. };
  3423. /**
  3424. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3425. * The cross product is then orthogonal to both "left" and "right"
  3426. * @param left defines the left operand
  3427. * @param right defines the right operand
  3428. * @returns the cross product
  3429. */
  3430. Vector3.Cross = function (left, right) {
  3431. var result = Vector3.Zero();
  3432. Vector3.CrossToRef(left, right, result);
  3433. return result;
  3434. };
  3435. /**
  3436. * Sets the passed vector "result" with the cross product of "left" and "right"
  3437. * The cross product is then orthogonal to both "left" and "right"
  3438. * @param left defines the left operand
  3439. * @param right defines the right operand
  3440. * @param result defines the Vector3 where to store the result
  3441. */
  3442. Vector3.CrossToRef = function (left, right, result) {
  3443. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3444. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3445. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3446. result.copyFrom(MathTmp.Vector3[0]);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 as the normalization of the passed vector
  3450. * @param vector defines the Vector3 to normalize
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Normalize = function (vector) {
  3454. var result = Vector3.Zero();
  3455. Vector3.NormalizeToRef(vector, result);
  3456. return result;
  3457. };
  3458. /**
  3459. * Sets the passed vector "result" with the normalization of the passed first vector
  3460. * @param vector defines the Vector3 to normalize
  3461. * @param result defines the Vector3 where to store the result
  3462. */
  3463. Vector3.NormalizeToRef = function (vector, result) {
  3464. result.copyFrom(vector);
  3465. result.normalize();
  3466. };
  3467. /**
  3468. * Project a Vector3 onto screen space
  3469. * @param vector defines the Vector3 to project
  3470. * @param world defines the world matrix to use
  3471. * @param transform defines the transform (view x projection) matrix to use
  3472. * @param viewport defines the screen viewport to use
  3473. * @returns the new Vector3
  3474. */
  3475. Vector3.Project = function (vector, world, transform, viewport) {
  3476. var cw = viewport.width;
  3477. var ch = viewport.height;
  3478. var cx = viewport.x;
  3479. var cy = viewport.y;
  3480. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3481. 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);
  3482. var matrix = MathTmp.Matrix[0];
  3483. world.multiplyToRef(transform, matrix);
  3484. matrix.multiplyToRef(viewportMatrix, matrix);
  3485. return Vector3.TransformCoordinates(vector, matrix);
  3486. };
  3487. /**
  3488. * Unproject from screen space to object space
  3489. * @param source defines the screen space Vector3 to use
  3490. * @param viewportWidth defines the current width of the viewport
  3491. * @param viewportHeight defines the current height of the viewport
  3492. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3493. * @param transform defines the transform (view x projection) matrix to use
  3494. * @returns the new Vector3
  3495. */
  3496. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3497. var matrix = MathTmp.Matrix[0];
  3498. world.multiplyToRef(transform, matrix);
  3499. matrix.invert();
  3500. source.x = source.x / viewportWidth * 2 - 1;
  3501. source.y = -(source.y / viewportHeight * 2 - 1);
  3502. var vector = Vector3.TransformCoordinates(source, matrix);
  3503. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3504. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3505. vector = vector.scale(1.0 / num);
  3506. }
  3507. return vector;
  3508. };
  3509. /**
  3510. * Unproject from screen space to object space
  3511. * @param source defines the screen space Vector3 to use
  3512. * @param viewportWidth defines the current width of the viewport
  3513. * @param viewportHeight defines the current height of the viewport
  3514. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3515. * @param view defines the view matrix to use
  3516. * @param projection defines the projection matrix to use
  3517. * @returns the new Vector3
  3518. */
  3519. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3520. var result = Vector3.Zero();
  3521. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3522. return result;
  3523. };
  3524. /**
  3525. * Unproject from screen space to object space
  3526. * @param source defines the screen space Vector3 to use
  3527. * @param viewportWidth defines the current width of the viewport
  3528. * @param viewportHeight defines the current height of the viewport
  3529. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3530. * @param view defines the view matrix to use
  3531. * @param projection defines the projection matrix to use
  3532. * @param result defines the Vector3 where to store the result
  3533. */
  3534. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3535. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3536. };
  3537. /**
  3538. * Unproject from screen space to object space
  3539. * @param sourceX defines the screen space x coordinate to use
  3540. * @param sourceY defines the screen space y coordinate to use
  3541. * @param sourceZ defines the screen space z coordinate to use
  3542. * @param viewportWidth defines the current width of the viewport
  3543. * @param viewportHeight defines the current height of the viewport
  3544. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3545. * @param view defines the view matrix to use
  3546. * @param projection defines the projection matrix to use
  3547. * @param result defines the Vector3 where to store the result
  3548. */
  3549. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3550. var matrix = MathTmp.Matrix[0];
  3551. world.multiplyToRef(view, matrix);
  3552. matrix.multiplyToRef(projection, matrix);
  3553. matrix.invert();
  3554. var screenSource = MathTmp.Vector3[0];
  3555. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3556. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3557. screenSource.z = 2 * sourceZ - 1.0;
  3558. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3559. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3560. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3561. result.scaleInPlace(1.0 / num);
  3562. }
  3563. };
  3564. /**
  3565. * Gets the minimal coordinate values between two Vector3
  3566. * @param left defines the first operand
  3567. * @param right defines the second operand
  3568. * @returns the new Vector3
  3569. */
  3570. Vector3.Minimize = function (left, right) {
  3571. var min = left.clone();
  3572. min.minimizeInPlace(right);
  3573. return min;
  3574. };
  3575. /**
  3576. * Gets the maximal coordinate values between two Vector3
  3577. * @param left defines the first operand
  3578. * @param right defines the second operand
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.Maximize = function (left, right) {
  3582. var max = left.clone();
  3583. max.maximizeInPlace(right);
  3584. return max;
  3585. };
  3586. /**
  3587. * Returns the distance between the vectors "value1" and "value2"
  3588. * @param value1 defines the first operand
  3589. * @param value2 defines the second operand
  3590. * @returns the distance
  3591. */
  3592. Vector3.Distance = function (value1, value2) {
  3593. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3594. };
  3595. /**
  3596. * Returns the squared distance between the vectors "value1" and "value2"
  3597. * @param value1 defines the first operand
  3598. * @param value2 defines the second operand
  3599. * @returns the squared distance
  3600. */
  3601. Vector3.DistanceSquared = function (value1, value2) {
  3602. var x = value1.x - value2.x;
  3603. var y = value1.y - value2.y;
  3604. var z = value1.z - value2.z;
  3605. return (x * x) + (y * y) + (z * z);
  3606. };
  3607. /**
  3608. * Returns a new Vector3 located at the center between "value1" and "value2"
  3609. * @param value1 defines the first operand
  3610. * @param value2 defines the second operand
  3611. * @returns the new Vector3
  3612. */
  3613. Vector3.Center = function (value1, value2) {
  3614. var center = value1.add(value2);
  3615. center.scaleInPlace(0.5);
  3616. return center;
  3617. };
  3618. /**
  3619. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3620. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3621. * to something in order to rotate it from its local system to the given target system
  3622. * Note: axis1, axis2 and axis3 are normalized during this operation
  3623. * @param axis1 defines the first axis
  3624. * @param axis2 defines the second axis
  3625. * @param axis3 defines the third axis
  3626. * @returns a new Vector3
  3627. */
  3628. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3629. var rotation = Vector3.Zero();
  3630. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3631. return rotation;
  3632. };
  3633. /**
  3634. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3635. * @param axis1 defines the first axis
  3636. * @param axis2 defines the second axis
  3637. * @param axis3 defines the third axis
  3638. * @param ref defines the Vector3 where to store the result
  3639. */
  3640. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3641. var quat = MathTmp.Quaternion[0];
  3642. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3643. quat.toEulerAnglesToRef(ref);
  3644. };
  3645. return Vector3;
  3646. }());
  3647. BABYLON.Vector3 = Vector3;
  3648. //Vector4 class created for EulerAngle class conversion to Quaternion
  3649. var Vector4 = /** @class */ (function () {
  3650. /**
  3651. * Creates a Vector4 object from the passed floats.
  3652. */
  3653. function Vector4(x, y, z, w) {
  3654. this.x = x;
  3655. this.y = y;
  3656. this.z = z;
  3657. this.w = w;
  3658. }
  3659. /**
  3660. * Returns the string with the Vector4 coordinates.
  3661. */
  3662. Vector4.prototype.toString = function () {
  3663. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3664. };
  3665. /**
  3666. * Returns the string "Vector4".
  3667. */
  3668. Vector4.prototype.getClassName = function () {
  3669. return "Vector4";
  3670. };
  3671. /**
  3672. * Returns the Vector4 hash code.
  3673. */
  3674. Vector4.prototype.getHashCode = function () {
  3675. var hash = this.x || 0;
  3676. hash = (hash * 397) ^ (this.y || 0);
  3677. hash = (hash * 397) ^ (this.z || 0);
  3678. hash = (hash * 397) ^ (this.w || 0);
  3679. return hash;
  3680. };
  3681. // Operators
  3682. /**
  3683. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3684. */
  3685. Vector4.prototype.asArray = function () {
  3686. var result = new Array();
  3687. this.toArray(result, 0);
  3688. return result;
  3689. };
  3690. /**
  3691. * Populates the passed array from the passed index with the Vector4 coordinates.
  3692. * Returns the Vector4.
  3693. */
  3694. Vector4.prototype.toArray = function (array, index) {
  3695. if (index === undefined) {
  3696. index = 0;
  3697. }
  3698. array[index] = this.x;
  3699. array[index + 1] = this.y;
  3700. array[index + 2] = this.z;
  3701. array[index + 3] = this.w;
  3702. return this;
  3703. };
  3704. /**
  3705. * Adds the passed vector to the current Vector4.
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.addInPlace = function (otherVector) {
  3709. this.x += otherVector.x;
  3710. this.y += otherVector.y;
  3711. this.z += otherVector.z;
  3712. this.w += otherVector.w;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3717. */
  3718. Vector4.prototype.add = function (otherVector) {
  3719. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3720. };
  3721. /**
  3722. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.addToRef = function (otherVector, result) {
  3726. result.x = this.x + otherVector.x;
  3727. result.y = this.y + otherVector.y;
  3728. result.z = this.z + otherVector.z;
  3729. result.w = this.w + otherVector.w;
  3730. return this;
  3731. };
  3732. /**
  3733. * Subtract in place the passed vector from the current Vector4.
  3734. * Returns the updated Vector4.
  3735. */
  3736. Vector4.prototype.subtractInPlace = function (otherVector) {
  3737. this.x -= otherVector.x;
  3738. this.y -= otherVector.y;
  3739. this.z -= otherVector.z;
  3740. this.w -= otherVector.w;
  3741. return this;
  3742. };
  3743. /**
  3744. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3745. */
  3746. Vector4.prototype.subtract = function (otherVector) {
  3747. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3748. };
  3749. /**
  3750. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3751. * Returns the current Vector4.
  3752. */
  3753. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3754. result.x = this.x - otherVector.x;
  3755. result.y = this.y - otherVector.y;
  3756. result.z = this.z - otherVector.z;
  3757. result.w = this.w - otherVector.w;
  3758. return this;
  3759. };
  3760. /**
  3761. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3764. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3765. };
  3766. /**
  3767. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3768. * Returns the current Vector4.
  3769. */
  3770. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3771. result.x = this.x - x;
  3772. result.y = this.y - y;
  3773. result.z = this.z - z;
  3774. result.w = this.w - w;
  3775. return this;
  3776. };
  3777. /**
  3778. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3779. */
  3780. Vector4.prototype.negate = function () {
  3781. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3782. };
  3783. /**
  3784. * Multiplies the current Vector4 coordinates by scale (float).
  3785. * Returns the updated Vector4.
  3786. */
  3787. Vector4.prototype.scaleInPlace = function (scale) {
  3788. this.x *= scale;
  3789. this.y *= scale;
  3790. this.z *= scale;
  3791. this.w *= scale;
  3792. return this;
  3793. };
  3794. /**
  3795. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3796. */
  3797. Vector4.prototype.scale = function (scale) {
  3798. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3799. };
  3800. /**
  3801. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3802. * Returns the current Vector4.
  3803. */
  3804. Vector4.prototype.scaleToRef = function (scale, result) {
  3805. result.x = this.x * scale;
  3806. result.y = this.y * scale;
  3807. result.z = this.z * scale;
  3808. result.w = this.w * scale;
  3809. return this;
  3810. };
  3811. /**
  3812. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3813. * @param scale defines the scale factor
  3814. * @param result defines the Vector4 object where to store the result
  3815. * @returns the unmodified current Vector4
  3816. */
  3817. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3818. result.x += this.x * scale;
  3819. result.y += this.y * scale;
  3820. result.z += this.z * scale;
  3821. result.w += this.w * scale;
  3822. return this;
  3823. };
  3824. /**
  3825. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3826. */
  3827. Vector4.prototype.equals = function (otherVector) {
  3828. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3829. };
  3830. /**
  3831. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3832. */
  3833. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3834. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3835. return otherVector
  3836. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3837. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3838. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3839. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3840. };
  3841. /**
  3842. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3843. */
  3844. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3845. return this.x === x && this.y === y && this.z === z && this.w === w;
  3846. };
  3847. /**
  3848. * Multiplies in place the current Vector4 by the passed one.
  3849. * Returns the updated Vector4.
  3850. */
  3851. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3852. this.x *= otherVector.x;
  3853. this.y *= otherVector.y;
  3854. this.z *= otherVector.z;
  3855. this.w *= otherVector.w;
  3856. return this;
  3857. };
  3858. /**
  3859. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3860. */
  3861. Vector4.prototype.multiply = function (otherVector) {
  3862. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3863. };
  3864. /**
  3865. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3866. * Returns the current Vector4.
  3867. */
  3868. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3869. result.x = this.x * otherVector.x;
  3870. result.y = this.y * otherVector.y;
  3871. result.z = this.z * otherVector.z;
  3872. result.w = this.w * otherVector.w;
  3873. return this;
  3874. };
  3875. /**
  3876. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3877. */
  3878. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3879. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3880. };
  3881. /**
  3882. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3883. */
  3884. Vector4.prototype.divide = function (otherVector) {
  3885. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3886. };
  3887. /**
  3888. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3889. * Returns the current Vector4.
  3890. */
  3891. Vector4.prototype.divideToRef = function (otherVector, result) {
  3892. result.x = this.x / otherVector.x;
  3893. result.y = this.y / otherVector.y;
  3894. result.z = this.z / otherVector.z;
  3895. result.w = this.w / otherVector.w;
  3896. return this;
  3897. };
  3898. /**
  3899. * Divides the current Vector3 coordinates by the passed ones.
  3900. * @returns the updated Vector3.
  3901. */
  3902. Vector4.prototype.divideInPlace = function (otherVector) {
  3903. return this.divideToRef(otherVector, this);
  3904. };
  3905. /**
  3906. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3907. * @param other defines the second operand
  3908. * @returns the current updated Vector4
  3909. */
  3910. Vector4.prototype.minimizeInPlace = function (other) {
  3911. if (other.x < this.x)
  3912. this.x = other.x;
  3913. if (other.y < this.y)
  3914. this.y = other.y;
  3915. if (other.z < this.z)
  3916. this.z = other.z;
  3917. if (other.w < this.w)
  3918. this.w = other.w;
  3919. return this;
  3920. };
  3921. /**
  3922. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3923. * @param other defines the second operand
  3924. * @returns the current updated Vector4
  3925. */
  3926. Vector4.prototype.maximizeInPlace = function (other) {
  3927. if (other.x > this.x)
  3928. this.x = other.x;
  3929. if (other.y > this.y)
  3930. this.y = other.y;
  3931. if (other.z > this.z)
  3932. this.z = other.z;
  3933. if (other.w > this.w)
  3934. this.w = other.w;
  3935. return this;
  3936. };
  3937. // Properties
  3938. /**
  3939. * Returns the Vector4 length (float).
  3940. */
  3941. Vector4.prototype.length = function () {
  3942. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3943. };
  3944. /**
  3945. * Returns the Vector4 squared length (float).
  3946. */
  3947. Vector4.prototype.lengthSquared = function () {
  3948. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3949. };
  3950. // Methods
  3951. /**
  3952. * Normalizes in place the Vector4.
  3953. * Returns the updated Vector4.
  3954. */
  3955. Vector4.prototype.normalize = function () {
  3956. var len = this.length();
  3957. if (len === 0)
  3958. return this;
  3959. var num = 1.0 / len;
  3960. this.x *= num;
  3961. this.y *= num;
  3962. this.z *= num;
  3963. this.w *= num;
  3964. return this;
  3965. };
  3966. /**
  3967. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3968. */
  3969. Vector4.prototype.toVector3 = function () {
  3970. return new Vector3(this.x, this.y, this.z);
  3971. };
  3972. /**
  3973. * Returns a new Vector4 copied from the current one.
  3974. */
  3975. Vector4.prototype.clone = function () {
  3976. return new Vector4(this.x, this.y, this.z, this.w);
  3977. };
  3978. /**
  3979. * Updates the current Vector4 with the passed one coordinates.
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.copyFrom = function (source) {
  3983. this.x = source.x;
  3984. this.y = source.y;
  3985. this.z = source.z;
  3986. this.w = source.w;
  3987. return this;
  3988. };
  3989. /**
  3990. * Updates the current Vector4 coordinates with the passed floats.
  3991. * Returns the updated Vector4.
  3992. */
  3993. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3994. this.x = x;
  3995. this.y = y;
  3996. this.z = z;
  3997. this.w = w;
  3998. return this;
  3999. };
  4000. /**
  4001. * Updates the current Vector4 coordinates with the passed floats.
  4002. * Returns the updated Vector4.
  4003. */
  4004. Vector4.prototype.set = function (x, y, z, w) {
  4005. return this.copyFromFloats(x, y, z, w);
  4006. };
  4007. // Statics
  4008. /**
  4009. * Returns a new Vector4 set from the starting index of the passed array.
  4010. */
  4011. Vector4.FromArray = function (array, offset) {
  4012. if (!offset) {
  4013. offset = 0;
  4014. }
  4015. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4016. };
  4017. /**
  4018. * Updates the passed vector "result" from the starting index of the passed array.
  4019. */
  4020. Vector4.FromArrayToRef = function (array, offset, result) {
  4021. result.x = array[offset];
  4022. result.y = array[offset + 1];
  4023. result.z = array[offset + 2];
  4024. result.w = array[offset + 3];
  4025. };
  4026. /**
  4027. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4028. */
  4029. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4030. Vector4.FromArrayToRef(array, offset, result);
  4031. };
  4032. /**
  4033. * Updates the passed vector "result" coordinates from the passed floats.
  4034. */
  4035. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4036. result.x = x;
  4037. result.y = y;
  4038. result.z = z;
  4039. result.w = w;
  4040. };
  4041. /**
  4042. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4043. */
  4044. Vector4.Zero = function () {
  4045. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4046. };
  4047. /**
  4048. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4049. */
  4050. Vector4.One = function () {
  4051. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4052. };
  4053. /**
  4054. * Returns a new normalized Vector4 from the passed one.
  4055. */
  4056. Vector4.Normalize = function (vector) {
  4057. var result = Vector4.Zero();
  4058. Vector4.NormalizeToRef(vector, result);
  4059. return result;
  4060. };
  4061. /**
  4062. * Updates the passed vector "result" from the normalization of the passed one.
  4063. */
  4064. Vector4.NormalizeToRef = function (vector, result) {
  4065. result.copyFrom(vector);
  4066. result.normalize();
  4067. };
  4068. Vector4.Minimize = function (left, right) {
  4069. var min = left.clone();
  4070. min.minimizeInPlace(right);
  4071. return min;
  4072. };
  4073. Vector4.Maximize = function (left, right) {
  4074. var max = left.clone();
  4075. max.maximizeInPlace(right);
  4076. return max;
  4077. };
  4078. /**
  4079. * Returns the distance (float) between the vectors "value1" and "value2".
  4080. */
  4081. Vector4.Distance = function (value1, value2) {
  4082. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4083. };
  4084. /**
  4085. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4086. */
  4087. Vector4.DistanceSquared = function (value1, value2) {
  4088. var x = value1.x - value2.x;
  4089. var y = value1.y - value2.y;
  4090. var z = value1.z - value2.z;
  4091. var w = value1.w - value2.w;
  4092. return (x * x) + (y * y) + (z * z) + (w * w);
  4093. };
  4094. /**
  4095. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4096. */
  4097. Vector4.Center = function (value1, value2) {
  4098. var center = value1.add(value2);
  4099. center.scaleInPlace(0.5);
  4100. return center;
  4101. };
  4102. /**
  4103. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4104. * This methods computes transformed normalized direction vectors only.
  4105. */
  4106. Vector4.TransformNormal = function (vector, transformation) {
  4107. var result = Vector4.Zero();
  4108. Vector4.TransformNormalToRef(vector, transformation, result);
  4109. return result;
  4110. };
  4111. /**
  4112. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4113. * This methods computes transformed normalized direction vectors only.
  4114. */
  4115. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4116. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4117. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4118. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4119. result.x = x;
  4120. result.y = y;
  4121. result.z = z;
  4122. result.w = vector.w;
  4123. };
  4124. /**
  4125. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4126. * This methods computes transformed normalized direction vectors only.
  4127. */
  4128. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4129. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4130. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4131. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4132. result.w = w;
  4133. };
  4134. return Vector4;
  4135. }());
  4136. BABYLON.Vector4 = Vector4;
  4137. var Size = /** @class */ (function () {
  4138. /**
  4139. * Creates a Size object from the passed width and height (floats).
  4140. */
  4141. function Size(width, height) {
  4142. this.width = width;
  4143. this.height = height;
  4144. }
  4145. // Returns a string with the Size width and height.
  4146. Size.prototype.toString = function () {
  4147. return "{W: " + this.width + ", H: " + this.height + "}";
  4148. };
  4149. /**
  4150. * Returns the string "Size"
  4151. */
  4152. Size.prototype.getClassName = function () {
  4153. return "Size";
  4154. };
  4155. /**
  4156. * Returns the Size hash code.
  4157. */
  4158. Size.prototype.getHashCode = function () {
  4159. var hash = this.width || 0;
  4160. hash = (hash * 397) ^ (this.height || 0);
  4161. return hash;
  4162. };
  4163. /**
  4164. * Updates the current size from the passed one.
  4165. * Returns the updated Size.
  4166. */
  4167. Size.prototype.copyFrom = function (src) {
  4168. this.width = src.width;
  4169. this.height = src.height;
  4170. };
  4171. /**
  4172. * Updates in place the current Size from the passed floats.
  4173. * Returns the updated Size.
  4174. */
  4175. Size.prototype.copyFromFloats = function (width, height) {
  4176. this.width = width;
  4177. this.height = height;
  4178. return this;
  4179. };
  4180. /**
  4181. * Updates in place the current Size from the passed floats.
  4182. * Returns the updated Size.
  4183. */
  4184. Size.prototype.set = function (width, height) {
  4185. return this.copyFromFloats(width, height);
  4186. };
  4187. /**
  4188. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4189. */
  4190. Size.prototype.multiplyByFloats = function (w, h) {
  4191. return new Size(this.width * w, this.height * h);
  4192. };
  4193. /**
  4194. * Returns a new Size copied from the passed one.
  4195. */
  4196. Size.prototype.clone = function () {
  4197. return new Size(this.width, this.height);
  4198. };
  4199. /**
  4200. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4201. */
  4202. Size.prototype.equals = function (other) {
  4203. if (!other) {
  4204. return false;
  4205. }
  4206. return (this.width === other.width) && (this.height === other.height);
  4207. };
  4208. Object.defineProperty(Size.prototype, "surface", {
  4209. /**
  4210. * Returns the surface of the Size : width * height (float).
  4211. */
  4212. get: function () {
  4213. return this.width * this.height;
  4214. },
  4215. enumerable: true,
  4216. configurable: true
  4217. });
  4218. /**
  4219. * Returns a new Size set to (0.0, 0.0)
  4220. */
  4221. Size.Zero = function () {
  4222. return new Size(0.0, 0.0);
  4223. };
  4224. /**
  4225. * Returns a new Size set as the addition result of the current Size and the passed one.
  4226. */
  4227. Size.prototype.add = function (otherSize) {
  4228. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4229. return r;
  4230. };
  4231. /**
  4232. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4233. */
  4234. Size.prototype.subtract = function (otherSize) {
  4235. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4236. return r;
  4237. };
  4238. /**
  4239. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4240. */
  4241. Size.Lerp = function (start, end, amount) {
  4242. var w = start.width + ((end.width - start.width) * amount);
  4243. var h = start.height + ((end.height - start.height) * amount);
  4244. return new Size(w, h);
  4245. };
  4246. return Size;
  4247. }());
  4248. BABYLON.Size = Size;
  4249. var Quaternion = /** @class */ (function () {
  4250. /**
  4251. * Creates a new Quaternion from the passed floats.
  4252. */
  4253. function Quaternion(x, y, z, w) {
  4254. if (x === void 0) { x = 0.0; }
  4255. if (y === void 0) { y = 0.0; }
  4256. if (z === void 0) { z = 0.0; }
  4257. if (w === void 0) { w = 1.0; }
  4258. this.x = x;
  4259. this.y = y;
  4260. this.z = z;
  4261. this.w = w;
  4262. }
  4263. /**
  4264. * Returns a string with the Quaternion coordinates.
  4265. */
  4266. Quaternion.prototype.toString = function () {
  4267. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4268. };
  4269. /**
  4270. * Returns the string "Quaternion".
  4271. */
  4272. Quaternion.prototype.getClassName = function () {
  4273. return "Quaternion";
  4274. };
  4275. /**
  4276. * Returns the Quaternion hash code.
  4277. */
  4278. Quaternion.prototype.getHashCode = function () {
  4279. var hash = this.x || 0;
  4280. hash = (hash * 397) ^ (this.y || 0);
  4281. hash = (hash * 397) ^ (this.z || 0);
  4282. hash = (hash * 397) ^ (this.w || 0);
  4283. return hash;
  4284. };
  4285. /**
  4286. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4287. */
  4288. Quaternion.prototype.asArray = function () {
  4289. return [this.x, this.y, this.z, this.w];
  4290. };
  4291. /**
  4292. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4293. */
  4294. Quaternion.prototype.equals = function (otherQuaternion) {
  4295. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4296. };
  4297. /**
  4298. * Returns a new Quaternion copied from the current one.
  4299. */
  4300. Quaternion.prototype.clone = function () {
  4301. return new Quaternion(this.x, this.y, this.z, this.w);
  4302. };
  4303. /**
  4304. * Updates the current Quaternion from the passed one coordinates.
  4305. * Returns the updated Quaterion.
  4306. */
  4307. Quaternion.prototype.copyFrom = function (other) {
  4308. this.x = other.x;
  4309. this.y = other.y;
  4310. this.z = other.z;
  4311. this.w = other.w;
  4312. return this;
  4313. };
  4314. /**
  4315. * Updates the current Quaternion from the passed float coordinates.
  4316. * Returns the updated Quaterion.
  4317. */
  4318. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4319. this.x = x;
  4320. this.y = y;
  4321. this.z = z;
  4322. this.w = w;
  4323. return this;
  4324. };
  4325. /**
  4326. * Updates the current Quaternion from the passed float coordinates.
  4327. * Returns the updated Quaterion.
  4328. */
  4329. Quaternion.prototype.set = function (x, y, z, w) {
  4330. return this.copyFromFloats(x, y, z, w);
  4331. };
  4332. /**
  4333. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4334. */
  4335. Quaternion.prototype.add = function (other) {
  4336. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4337. };
  4338. /**
  4339. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4340. */
  4341. Quaternion.prototype.subtract = function (other) {
  4342. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4343. };
  4344. /**
  4345. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4346. */
  4347. Quaternion.prototype.scale = function (value) {
  4348. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4349. };
  4350. /**
  4351. * Scale the current Quaternion values by a factor to a given Quaternion
  4352. * @param scale defines the scale factor
  4353. * @param result defines the Quaternion object where to store the result
  4354. * @returns the unmodified current Quaternion
  4355. */
  4356. Quaternion.prototype.scaleToRef = function (scale, result) {
  4357. result.x = this.x * scale;
  4358. result.y = this.y * scale;
  4359. result.z = this.z * scale;
  4360. result.w = this.w * scale;
  4361. return this;
  4362. };
  4363. /**
  4364. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4365. * @param scale defines the scale factor
  4366. * @param result defines the Quaternion object where to store the result
  4367. * @returns the unmodified current Quaternion
  4368. */
  4369. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4370. result.x += this.x * scale;
  4371. result.y += this.y * scale;
  4372. result.z += this.z * scale;
  4373. result.w += this.w * scale;
  4374. return this;
  4375. };
  4376. /**
  4377. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4378. */
  4379. Quaternion.prototype.multiply = function (q1) {
  4380. var result = new Quaternion(0, 0, 0, 1.0);
  4381. this.multiplyToRef(q1, result);
  4382. return result;
  4383. };
  4384. /**
  4385. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4386. * Returns the current Quaternion.
  4387. */
  4388. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4389. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4390. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4391. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4392. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4393. result.copyFromFloats(x, y, z, w);
  4394. return this;
  4395. };
  4396. /**
  4397. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4398. * Returns the updated Quaternion.
  4399. */
  4400. Quaternion.prototype.multiplyInPlace = function (q1) {
  4401. this.multiplyToRef(q1, this);
  4402. return this;
  4403. };
  4404. /**
  4405. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4406. * Returns the current Quaternion.
  4407. */
  4408. Quaternion.prototype.conjugateToRef = function (ref) {
  4409. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4410. return this;
  4411. };
  4412. /**
  4413. * Conjugates in place the current Quaternion.
  4414. * Returns the updated Quaternion.
  4415. */
  4416. Quaternion.prototype.conjugateInPlace = function () {
  4417. this.x *= -1;
  4418. this.y *= -1;
  4419. this.z *= -1;
  4420. return this;
  4421. };
  4422. /**
  4423. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4424. */
  4425. Quaternion.prototype.conjugate = function () {
  4426. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4427. return result;
  4428. };
  4429. /**
  4430. * Returns the Quaternion length (float).
  4431. */
  4432. Quaternion.prototype.length = function () {
  4433. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4434. };
  4435. /**
  4436. * Normalize in place the current Quaternion.
  4437. * Returns the updated Quaternion.
  4438. */
  4439. Quaternion.prototype.normalize = function () {
  4440. var length = 1.0 / this.length();
  4441. this.x *= length;
  4442. this.y *= length;
  4443. this.z *= length;
  4444. this.w *= length;
  4445. return this;
  4446. };
  4447. /**
  4448. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4449. * @param order is a reserved parameter and is ignore for now
  4450. * @returns the new Vector3
  4451. */
  4452. Quaternion.prototype.toEulerAngles = function (order) {
  4453. if (order === void 0) { order = "YZX"; }
  4454. var result = Vector3.Zero();
  4455. this.toEulerAnglesToRef(result, order);
  4456. return result;
  4457. };
  4458. /**
  4459. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4460. * @param result defines the vector which will be filled with the Euler angles
  4461. * @param order is a reserved parameter and is ignore for now
  4462. * @returns the current Quaternion
  4463. */
  4464. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4465. if (order === void 0) { order = "YZX"; }
  4466. var qz = this.z;
  4467. var qx = this.x;
  4468. var qy = this.y;
  4469. var qw = this.w;
  4470. var sqw = qw * qw;
  4471. var sqz = qz * qz;
  4472. var sqx = qx * qx;
  4473. var sqy = qy * qy;
  4474. var zAxisY = qy * qz - qx * qw;
  4475. var limit = .4999999;
  4476. if (zAxisY < -limit) {
  4477. result.y = 2 * Math.atan2(qy, qw);
  4478. result.x = Math.PI / 2;
  4479. result.z = 0;
  4480. }
  4481. else if (zAxisY > limit) {
  4482. result.y = 2 * Math.atan2(qy, qw);
  4483. result.x = -Math.PI / 2;
  4484. result.z = 0;
  4485. }
  4486. else {
  4487. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4488. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4489. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4490. }
  4491. return this;
  4492. };
  4493. /**
  4494. * Updates the passed rotation matrix with the current Quaternion values.
  4495. * Returns the current Quaternion.
  4496. */
  4497. Quaternion.prototype.toRotationMatrix = function (result) {
  4498. var xx = this.x * this.x;
  4499. var yy = this.y * this.y;
  4500. var zz = this.z * this.z;
  4501. var xy = this.x * this.y;
  4502. var zw = this.z * this.w;
  4503. var zx = this.z * this.x;
  4504. var yw = this.y * this.w;
  4505. var yz = this.y * this.z;
  4506. var xw = this.x * this.w;
  4507. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4508. result.m[1] = 2.0 * (xy + zw);
  4509. result.m[2] = 2.0 * (zx - yw);
  4510. result.m[3] = 0;
  4511. result.m[4] = 2.0 * (xy - zw);
  4512. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4513. result.m[6] = 2.0 * (yz + xw);
  4514. result.m[7] = 0;
  4515. result.m[8] = 2.0 * (zx + yw);
  4516. result.m[9] = 2.0 * (yz - xw);
  4517. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4518. result.m[11] = 0;
  4519. result.m[12] = 0;
  4520. result.m[13] = 0;
  4521. result.m[14] = 0;
  4522. result.m[15] = 1.0;
  4523. result._markAsUpdated();
  4524. return this;
  4525. };
  4526. /**
  4527. * Updates the current Quaternion from the passed rotation matrix values.
  4528. * Returns the updated Quaternion.
  4529. */
  4530. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4531. Quaternion.FromRotationMatrixToRef(matrix, this);
  4532. return this;
  4533. };
  4534. // Statics
  4535. /**
  4536. * Returns a new Quaternion set from the passed rotation matrix values.
  4537. */
  4538. Quaternion.FromRotationMatrix = function (matrix) {
  4539. var result = new Quaternion();
  4540. Quaternion.FromRotationMatrixToRef(matrix, result);
  4541. return result;
  4542. };
  4543. /**
  4544. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4545. */
  4546. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4547. var data = matrix.m;
  4548. var m11 = data[0], m12 = data[4], m13 = data[8];
  4549. var m21 = data[1], m22 = data[5], m23 = data[9];
  4550. var m31 = data[2], m32 = data[6], m33 = data[10];
  4551. var trace = m11 + m22 + m33;
  4552. var s;
  4553. if (trace > 0) {
  4554. s = 0.5 / Math.sqrt(trace + 1.0);
  4555. result.w = 0.25 / s;
  4556. result.x = (m32 - m23) * s;
  4557. result.y = (m13 - m31) * s;
  4558. result.z = (m21 - m12) * s;
  4559. }
  4560. else if (m11 > m22 && m11 > m33) {
  4561. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4562. result.w = (m32 - m23) / s;
  4563. result.x = 0.25 * s;
  4564. result.y = (m12 + m21) / s;
  4565. result.z = (m13 + m31) / s;
  4566. }
  4567. else if (m22 > m33) {
  4568. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4569. result.w = (m13 - m31) / s;
  4570. result.x = (m12 + m21) / s;
  4571. result.y = 0.25 * s;
  4572. result.z = (m23 + m32) / s;
  4573. }
  4574. else {
  4575. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4576. result.w = (m21 - m12) / s;
  4577. result.x = (m13 + m31) / s;
  4578. result.y = (m23 + m32) / s;
  4579. result.z = 0.25 * s;
  4580. }
  4581. };
  4582. /**
  4583. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4584. */
  4585. Quaternion.Zero = function () {
  4586. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4587. };
  4588. /**
  4589. * Returns a new Quaternion as the inverted current Quaternion.
  4590. */
  4591. Quaternion.Inverse = function (q) {
  4592. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4593. };
  4594. /**
  4595. * Returns the identity Quaternion.
  4596. */
  4597. Quaternion.Identity = function () {
  4598. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4599. };
  4600. Quaternion.IsIdentity = function (quaternion) {
  4601. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4602. };
  4603. /**
  4604. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4605. */
  4606. Quaternion.RotationAxis = function (axis, angle) {
  4607. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4608. };
  4609. /**
  4610. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4611. */
  4612. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4613. var sin = Math.sin(angle / 2);
  4614. axis.normalize();
  4615. result.w = Math.cos(angle / 2);
  4616. result.x = axis.x * sin;
  4617. result.y = axis.y * sin;
  4618. result.z = axis.z * sin;
  4619. return result;
  4620. };
  4621. /**
  4622. * Retuns a new Quaternion set from the starting index of the passed array.
  4623. */
  4624. Quaternion.FromArray = function (array, offset) {
  4625. if (!offset) {
  4626. offset = 0;
  4627. }
  4628. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4629. };
  4630. /**
  4631. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4632. */
  4633. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4634. var q = new Quaternion();
  4635. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4636. return q;
  4637. };
  4638. /**
  4639. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4640. */
  4641. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4642. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4643. var halfRoll = roll * 0.5;
  4644. var halfPitch = pitch * 0.5;
  4645. var halfYaw = yaw * 0.5;
  4646. var sinRoll = Math.sin(halfRoll);
  4647. var cosRoll = Math.cos(halfRoll);
  4648. var sinPitch = Math.sin(halfPitch);
  4649. var cosPitch = Math.cos(halfPitch);
  4650. var sinYaw = Math.sin(halfYaw);
  4651. var cosYaw = Math.cos(halfYaw);
  4652. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4653. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4654. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4655. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4656. };
  4657. /**
  4658. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4659. */
  4660. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4661. var result = new Quaternion();
  4662. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4663. return result;
  4664. };
  4665. /**
  4666. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4667. */
  4668. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4669. // Produces a quaternion from Euler angles in the z-x-z orientation
  4670. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4671. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4672. var halfBeta = beta * 0.5;
  4673. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4674. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4675. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4676. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4677. };
  4678. /**
  4679. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4680. * cf to Vector3.RotationFromAxis() documentation.
  4681. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4682. */
  4683. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4684. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4685. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4686. return quat;
  4687. };
  4688. /**
  4689. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4690. * cf to Vector3.RotationFromAxis() documentation.
  4691. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4692. */
  4693. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4694. var rotMat = MathTmp.Matrix[0];
  4695. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4696. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4697. };
  4698. Quaternion.Slerp = function (left, right, amount) {
  4699. var result = Quaternion.Identity();
  4700. Quaternion.SlerpToRef(left, right, amount, result);
  4701. return result;
  4702. };
  4703. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4704. var num2;
  4705. var num3;
  4706. var num = amount;
  4707. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4708. var flag = false;
  4709. if (num4 < 0) {
  4710. flag = true;
  4711. num4 = -num4;
  4712. }
  4713. if (num4 > 0.999999) {
  4714. num3 = 1 - num;
  4715. num2 = flag ? -num : num;
  4716. }
  4717. else {
  4718. var num5 = Math.acos(num4);
  4719. var num6 = (1.0 / Math.sin(num5));
  4720. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4721. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4722. }
  4723. result.x = (num3 * left.x) + (num2 * right.x);
  4724. result.y = (num3 * left.y) + (num2 * right.y);
  4725. result.z = (num3 * left.z) + (num2 * right.z);
  4726. result.w = (num3 * left.w) + (num2 * right.w);
  4727. };
  4728. /**
  4729. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4730. */
  4731. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4732. var squared = amount * amount;
  4733. var cubed = amount * squared;
  4734. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4735. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4736. var part3 = (cubed - (2.0 * squared)) + amount;
  4737. var part4 = cubed - squared;
  4738. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4739. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4740. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4741. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4742. return new Quaternion(x, y, z, w);
  4743. };
  4744. return Quaternion;
  4745. }());
  4746. BABYLON.Quaternion = Quaternion;
  4747. var Matrix = /** @class */ (function () {
  4748. function Matrix() {
  4749. this._isIdentity = false;
  4750. this._isIdentityDirty = true;
  4751. this.m = new Float32Array(16);
  4752. this._markAsUpdated();
  4753. }
  4754. Matrix.prototype._markAsUpdated = function () {
  4755. this.updateFlag = Matrix._updateFlagSeed++;
  4756. this._isIdentityDirty = true;
  4757. };
  4758. // Properties
  4759. /**
  4760. * Boolean : True is the matrix is the identity matrix
  4761. */
  4762. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4763. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4764. if (this._isIdentityDirty) {
  4765. this._isIdentityDirty = false;
  4766. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4767. this._isIdentity = false;
  4768. }
  4769. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4770. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4771. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4772. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4773. this._isIdentity = false;
  4774. }
  4775. else {
  4776. this._isIdentity = true;
  4777. }
  4778. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4779. this._isIdentity = false;
  4780. }
  4781. }
  4782. return this._isIdentity;
  4783. };
  4784. /**
  4785. * Returns the matrix determinant (float).
  4786. */
  4787. Matrix.prototype.determinant = function () {
  4788. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4789. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4790. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4791. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4792. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4793. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4794. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4795. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4796. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4797. };
  4798. // Methods
  4799. /**
  4800. * Returns the matrix underlying array.
  4801. */
  4802. Matrix.prototype.toArray = function () {
  4803. return this.m;
  4804. };
  4805. /**
  4806. * Returns the matrix underlying array.
  4807. */
  4808. Matrix.prototype.asArray = function () {
  4809. return this.toArray();
  4810. };
  4811. /**
  4812. * Inverts in place the Matrix.
  4813. * Returns the Matrix inverted.
  4814. */
  4815. Matrix.prototype.invert = function () {
  4816. this.invertToRef(this);
  4817. return this;
  4818. };
  4819. /**
  4820. * Sets all the matrix elements to zero.
  4821. * Returns the Matrix.
  4822. */
  4823. Matrix.prototype.reset = function () {
  4824. for (var index = 0; index < 16; index++) {
  4825. this.m[index] = 0.0;
  4826. }
  4827. this._markAsUpdated();
  4828. return this;
  4829. };
  4830. /**
  4831. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4832. */
  4833. Matrix.prototype.add = function (other) {
  4834. var result = new Matrix();
  4835. this.addToRef(other, result);
  4836. return result;
  4837. };
  4838. /**
  4839. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4840. * Returns the Matrix.
  4841. */
  4842. Matrix.prototype.addToRef = function (other, result) {
  4843. for (var index = 0; index < 16; index++) {
  4844. result.m[index] = this.m[index] + other.m[index];
  4845. }
  4846. result._markAsUpdated();
  4847. return this;
  4848. };
  4849. /**
  4850. * Adds in place the passed matrix to the current Matrix.
  4851. * Returns the updated Matrix.
  4852. */
  4853. Matrix.prototype.addToSelf = function (other) {
  4854. for (var index = 0; index < 16; index++) {
  4855. this.m[index] += other.m[index];
  4856. }
  4857. this._markAsUpdated();
  4858. return this;
  4859. };
  4860. /**
  4861. * Sets the passed matrix with the current inverted Matrix.
  4862. * Returns the unmodified current Matrix.
  4863. */
  4864. Matrix.prototype.invertToRef = function (other) {
  4865. var l1 = this.m[0];
  4866. var l2 = this.m[1];
  4867. var l3 = this.m[2];
  4868. var l4 = this.m[3];
  4869. var l5 = this.m[4];
  4870. var l6 = this.m[5];
  4871. var l7 = this.m[6];
  4872. var l8 = this.m[7];
  4873. var l9 = this.m[8];
  4874. var l10 = this.m[9];
  4875. var l11 = this.m[10];
  4876. var l12 = this.m[11];
  4877. var l13 = this.m[12];
  4878. var l14 = this.m[13];
  4879. var l15 = this.m[14];
  4880. var l16 = this.m[15];
  4881. var l17 = (l11 * l16) - (l12 * l15);
  4882. var l18 = (l10 * l16) - (l12 * l14);
  4883. var l19 = (l10 * l15) - (l11 * l14);
  4884. var l20 = (l9 * l16) - (l12 * l13);
  4885. var l21 = (l9 * l15) - (l11 * l13);
  4886. var l22 = (l9 * l14) - (l10 * l13);
  4887. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4888. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4889. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4890. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4891. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4892. var l28 = (l7 * l16) - (l8 * l15);
  4893. var l29 = (l6 * l16) - (l8 * l14);
  4894. var l30 = (l6 * l15) - (l7 * l14);
  4895. var l31 = (l5 * l16) - (l8 * l13);
  4896. var l32 = (l5 * l15) - (l7 * l13);
  4897. var l33 = (l5 * l14) - (l6 * l13);
  4898. var l34 = (l7 * l12) - (l8 * l11);
  4899. var l35 = (l6 * l12) - (l8 * l10);
  4900. var l36 = (l6 * l11) - (l7 * l10);
  4901. var l37 = (l5 * l12) - (l8 * l9);
  4902. var l38 = (l5 * l11) - (l7 * l9);
  4903. var l39 = (l5 * l10) - (l6 * l9);
  4904. other.m[0] = l23 * l27;
  4905. other.m[4] = l24 * l27;
  4906. other.m[8] = l25 * l27;
  4907. other.m[12] = l26 * l27;
  4908. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4909. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4910. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4911. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4912. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4913. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4914. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4915. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4916. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4917. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4918. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4919. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4920. other._markAsUpdated();
  4921. return this;
  4922. };
  4923. /**
  4924. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4925. * Returns the updated Matrix.
  4926. */
  4927. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4928. this.m[12] = x;
  4929. this.m[13] = y;
  4930. this.m[14] = z;
  4931. this._markAsUpdated();
  4932. return this;
  4933. };
  4934. /**
  4935. * Inserts the translation vector in the current Matrix.
  4936. * Returns the updated Matrix.
  4937. */
  4938. Matrix.prototype.setTranslation = function (vector3) {
  4939. this.m[12] = vector3.x;
  4940. this.m[13] = vector3.y;
  4941. this.m[14] = vector3.z;
  4942. this._markAsUpdated();
  4943. return this;
  4944. };
  4945. /**
  4946. * Returns a new Vector3 as the extracted translation from the Matrix.
  4947. */
  4948. Matrix.prototype.getTranslation = function () {
  4949. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4950. };
  4951. /**
  4952. * Fill a Vector3 with the extracted translation from the Matrix.
  4953. */
  4954. Matrix.prototype.getTranslationToRef = function (result) {
  4955. result.x = this.m[12];
  4956. result.y = this.m[13];
  4957. result.z = this.m[14];
  4958. return this;
  4959. };
  4960. /**
  4961. * Remove rotation and scaling part from the Matrix.
  4962. * Returns the updated Matrix.
  4963. */
  4964. Matrix.prototype.removeRotationAndScaling = function () {
  4965. this.setRowFromFloats(0, 1, 0, 0, 0);
  4966. this.setRowFromFloats(1, 0, 1, 0, 0);
  4967. this.setRowFromFloats(2, 0, 0, 1, 0);
  4968. return this;
  4969. };
  4970. /**
  4971. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4972. */
  4973. Matrix.prototype.multiply = function (other) {
  4974. var result = new Matrix();
  4975. this.multiplyToRef(other, result);
  4976. return result;
  4977. };
  4978. /**
  4979. * Updates the current Matrix from the passed one values.
  4980. * Returns the updated Matrix.
  4981. */
  4982. Matrix.prototype.copyFrom = function (other) {
  4983. for (var index = 0; index < 16; index++) {
  4984. this.m[index] = other.m[index];
  4985. }
  4986. this._markAsUpdated();
  4987. return this;
  4988. };
  4989. /**
  4990. * Populates the passed array from the starting index with the Matrix values.
  4991. * Returns the Matrix.
  4992. */
  4993. Matrix.prototype.copyToArray = function (array, offset) {
  4994. if (offset === void 0) { offset = 0; }
  4995. for (var index = 0; index < 16; index++) {
  4996. array[offset + index] = this.m[index];
  4997. }
  4998. return this;
  4999. };
  5000. /**
  5001. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5002. */
  5003. Matrix.prototype.multiplyToRef = function (other, result) {
  5004. this.multiplyToArray(other, result.m, 0);
  5005. result._markAsUpdated();
  5006. return this;
  5007. };
  5008. /**
  5009. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5010. */
  5011. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5012. var tm0 = this.m[0];
  5013. var tm1 = this.m[1];
  5014. var tm2 = this.m[2];
  5015. var tm3 = this.m[3];
  5016. var tm4 = this.m[4];
  5017. var tm5 = this.m[5];
  5018. var tm6 = this.m[6];
  5019. var tm7 = this.m[7];
  5020. var tm8 = this.m[8];
  5021. var tm9 = this.m[9];
  5022. var tm10 = this.m[10];
  5023. var tm11 = this.m[11];
  5024. var tm12 = this.m[12];
  5025. var tm13 = this.m[13];
  5026. var tm14 = this.m[14];
  5027. var tm15 = this.m[15];
  5028. var om0 = other.m[0];
  5029. var om1 = other.m[1];
  5030. var om2 = other.m[2];
  5031. var om3 = other.m[3];
  5032. var om4 = other.m[4];
  5033. var om5 = other.m[5];
  5034. var om6 = other.m[6];
  5035. var om7 = other.m[7];
  5036. var om8 = other.m[8];
  5037. var om9 = other.m[9];
  5038. var om10 = other.m[10];
  5039. var om11 = other.m[11];
  5040. var om12 = other.m[12];
  5041. var om13 = other.m[13];
  5042. var om14 = other.m[14];
  5043. var om15 = other.m[15];
  5044. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5045. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5046. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5047. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5048. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5049. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5050. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5051. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5052. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5053. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5054. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5055. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5056. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5057. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5058. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5059. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5060. return this;
  5061. };
  5062. /**
  5063. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5064. */
  5065. Matrix.prototype.equals = function (value) {
  5066. return value &&
  5067. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5068. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5069. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5070. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5071. };
  5072. /**
  5073. * Returns a new Matrix from the current Matrix.
  5074. */
  5075. Matrix.prototype.clone = function () {
  5076. 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]);
  5077. };
  5078. /**
  5079. * Returns the string "Matrix"
  5080. */
  5081. Matrix.prototype.getClassName = function () {
  5082. return "Matrix";
  5083. };
  5084. /**
  5085. * Returns the Matrix hash code.
  5086. */
  5087. Matrix.prototype.getHashCode = function () {
  5088. var hash = this.m[0] || 0;
  5089. for (var i = 1; i < 16; i++) {
  5090. hash = (hash * 397) ^ (this.m[i] || 0);
  5091. }
  5092. return hash;
  5093. };
  5094. /**
  5095. * Decomposes the current Matrix into :
  5096. * - a scale vector3 passed as a reference to update,
  5097. * - a rotation quaternion passed as a reference to update,
  5098. * - a translation vector3 passed as a reference to update.
  5099. * Returns the true if operation was successful.
  5100. */
  5101. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5102. translation.x = this.m[12];
  5103. translation.y = this.m[13];
  5104. translation.z = this.m[14];
  5105. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5106. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5107. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5108. if (this.determinant() <= 0) {
  5109. scale.y *= -1;
  5110. }
  5111. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5112. rotation.x = 0;
  5113. rotation.y = 0;
  5114. rotation.z = 0;
  5115. rotation.w = 1;
  5116. return false;
  5117. }
  5118. 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]);
  5119. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5120. return true;
  5121. };
  5122. /**
  5123. * Returns the index-th row of the current matrix as a new Vector4.
  5124. */
  5125. Matrix.prototype.getRow = function (index) {
  5126. if (index < 0 || index > 3) {
  5127. return null;
  5128. }
  5129. var i = index * 4;
  5130. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5131. };
  5132. /**
  5133. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5134. * Returns the updated Matrix.
  5135. */
  5136. Matrix.prototype.setRow = function (index, row) {
  5137. if (index < 0 || index > 3) {
  5138. return this;
  5139. }
  5140. var i = index * 4;
  5141. this.m[i + 0] = row.x;
  5142. this.m[i + 1] = row.y;
  5143. this.m[i + 2] = row.z;
  5144. this.m[i + 3] = row.w;
  5145. this._markAsUpdated();
  5146. return this;
  5147. };
  5148. /**
  5149. * Compute the transpose of the matrix.
  5150. * Returns a new Matrix.
  5151. */
  5152. Matrix.prototype.transpose = function () {
  5153. return Matrix.Transpose(this);
  5154. };
  5155. /**
  5156. * Compute the transpose of the matrix.
  5157. * Returns the current matrix.
  5158. */
  5159. Matrix.prototype.transposeToRef = function (result) {
  5160. Matrix.TransposeToRef(this, result);
  5161. return this;
  5162. };
  5163. /**
  5164. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5165. * Returns the updated Matrix.
  5166. */
  5167. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5168. if (index < 0 || index > 3) {
  5169. return this;
  5170. }
  5171. var i = index * 4;
  5172. this.m[i + 0] = x;
  5173. this.m[i + 1] = y;
  5174. this.m[i + 2] = z;
  5175. this.m[i + 3] = w;
  5176. this._markAsUpdated();
  5177. return this;
  5178. };
  5179. /**
  5180. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5181. * @param scale defines the scale factor
  5182. * @returns a new Matrix
  5183. */
  5184. Matrix.prototype.scale = function (scale) {
  5185. var result = new Matrix();
  5186. this.scaleToRef(scale, result);
  5187. return result;
  5188. };
  5189. /**
  5190. * Scale the current Matrix values by a factor to a given result Matrix
  5191. * @param scale defines the scale factor
  5192. * @param result defines the Matrix to store the result
  5193. * @returns the current Matrix
  5194. */
  5195. Matrix.prototype.scaleToRef = function (scale, result) {
  5196. for (var index = 0; index < 16; index++) {
  5197. result.m[index] = this.m[index] * scale;
  5198. }
  5199. result._markAsUpdated();
  5200. return this;
  5201. };
  5202. /**
  5203. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5204. * @param scale defines the scale factor
  5205. * @param result defines the Matrix to store the result
  5206. * @returns the current Matrix
  5207. */
  5208. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5209. for (var index = 0; index < 16; index++) {
  5210. result.m[index] += this.m[index] * scale;
  5211. }
  5212. result._markAsUpdated();
  5213. return this;
  5214. };
  5215. /**
  5216. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5217. * @param ref matrix to store the result
  5218. */
  5219. Matrix.prototype.toNormalMatrix = function (ref) {
  5220. this.invertToRef(ref);
  5221. ref.transpose();
  5222. var m = ref.m;
  5223. 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);
  5224. };
  5225. /**
  5226. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5227. */
  5228. Matrix.prototype.getRotationMatrix = function () {
  5229. var result = Matrix.Identity();
  5230. this.getRotationMatrixToRef(result);
  5231. return result;
  5232. };
  5233. /**
  5234. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5235. * Returns the current Matrix.
  5236. */
  5237. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5238. var m = this.m;
  5239. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5240. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5241. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5242. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5243. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5244. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5245. 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);
  5246. return this;
  5247. };
  5248. // Statics
  5249. /**
  5250. * Returns a new Matrix set from the starting index of the passed array.
  5251. */
  5252. Matrix.FromArray = function (array, offset) {
  5253. var result = new Matrix();
  5254. if (!offset) {
  5255. offset = 0;
  5256. }
  5257. Matrix.FromArrayToRef(array, offset, result);
  5258. return result;
  5259. };
  5260. /**
  5261. * Sets the passed "result" matrix from the starting index of the passed array.
  5262. */
  5263. Matrix.FromArrayToRef = function (array, offset, result) {
  5264. for (var index = 0; index < 16; index++) {
  5265. result.m[index] = array[index + offset];
  5266. }
  5267. result._markAsUpdated();
  5268. };
  5269. /**
  5270. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5271. */
  5272. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5273. for (var index = 0; index < 16; index++) {
  5274. result.m[index] = array[index + offset] * scale;
  5275. }
  5276. result._markAsUpdated();
  5277. };
  5278. /**
  5279. * Sets the passed matrix "result" with the 16 passed floats.
  5280. */
  5281. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5282. result.m[0] = initialM11;
  5283. result.m[1] = initialM12;
  5284. result.m[2] = initialM13;
  5285. result.m[3] = initialM14;
  5286. result.m[4] = initialM21;
  5287. result.m[5] = initialM22;
  5288. result.m[6] = initialM23;
  5289. result.m[7] = initialM24;
  5290. result.m[8] = initialM31;
  5291. result.m[9] = initialM32;
  5292. result.m[10] = initialM33;
  5293. result.m[11] = initialM34;
  5294. result.m[12] = initialM41;
  5295. result.m[13] = initialM42;
  5296. result.m[14] = initialM43;
  5297. result.m[15] = initialM44;
  5298. result._markAsUpdated();
  5299. };
  5300. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5301. /**
  5302. * Static identity matrix to be used as readonly matrix
  5303. * Must not be updated.
  5304. */
  5305. get: function () {
  5306. return Matrix._identityReadOnly;
  5307. },
  5308. enumerable: true,
  5309. configurable: true
  5310. });
  5311. /**
  5312. * Returns a new Matrix set from the 16 passed floats.
  5313. */
  5314. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5315. var result = new Matrix();
  5316. result.m[0] = initialM11;
  5317. result.m[1] = initialM12;
  5318. result.m[2] = initialM13;
  5319. result.m[3] = initialM14;
  5320. result.m[4] = initialM21;
  5321. result.m[5] = initialM22;
  5322. result.m[6] = initialM23;
  5323. result.m[7] = initialM24;
  5324. result.m[8] = initialM31;
  5325. result.m[9] = initialM32;
  5326. result.m[10] = initialM33;
  5327. result.m[11] = initialM34;
  5328. result.m[12] = initialM41;
  5329. result.m[13] = initialM42;
  5330. result.m[14] = initialM43;
  5331. result.m[15] = initialM44;
  5332. return result;
  5333. };
  5334. /**
  5335. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5336. */
  5337. Matrix.Compose = function (scale, rotation, translation) {
  5338. var result = Matrix.Identity();
  5339. Matrix.ComposeToRef(scale, rotation, translation, result);
  5340. return result;
  5341. };
  5342. /**
  5343. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5344. */
  5345. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5346. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5347. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5348. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5349. result.setTranslation(translation);
  5350. };
  5351. /**
  5352. * Returns a new indentity Matrix.
  5353. */
  5354. Matrix.Identity = function () {
  5355. 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);
  5356. };
  5357. /**
  5358. * Sets the passed "result" as an identity matrix.
  5359. */
  5360. Matrix.IdentityToRef = function (result) {
  5361. 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);
  5362. };
  5363. /**
  5364. * Returns a new zero Matrix.
  5365. */
  5366. Matrix.Zero = function () {
  5367. 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);
  5368. };
  5369. /**
  5370. * Returns a new rotation matrix for "angle" radians around the X axis.
  5371. */
  5372. Matrix.RotationX = function (angle) {
  5373. var result = new Matrix();
  5374. Matrix.RotationXToRef(angle, result);
  5375. return result;
  5376. };
  5377. /**
  5378. * Returns a new Matrix as the passed inverted one.
  5379. */
  5380. Matrix.Invert = function (source) {
  5381. var result = new Matrix();
  5382. source.invertToRef(result);
  5383. return result;
  5384. };
  5385. /**
  5386. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5387. */
  5388. Matrix.RotationXToRef = function (angle, result) {
  5389. var s = Math.sin(angle);
  5390. var c = Math.cos(angle);
  5391. result.m[0] = 1.0;
  5392. result.m[15] = 1.0;
  5393. result.m[5] = c;
  5394. result.m[10] = c;
  5395. result.m[9] = -s;
  5396. result.m[6] = s;
  5397. result.m[1] = 0.0;
  5398. result.m[2] = 0.0;
  5399. result.m[3] = 0.0;
  5400. result.m[4] = 0.0;
  5401. result.m[7] = 0.0;
  5402. result.m[8] = 0.0;
  5403. result.m[11] = 0.0;
  5404. result.m[12] = 0.0;
  5405. result.m[13] = 0.0;
  5406. result.m[14] = 0.0;
  5407. result._markAsUpdated();
  5408. };
  5409. /**
  5410. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5411. */
  5412. Matrix.RotationY = function (angle) {
  5413. var result = new Matrix();
  5414. Matrix.RotationYToRef(angle, result);
  5415. return result;
  5416. };
  5417. /**
  5418. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5419. */
  5420. Matrix.RotationYToRef = function (angle, result) {
  5421. var s = Math.sin(angle);
  5422. var c = Math.cos(angle);
  5423. result.m[5] = 1.0;
  5424. result.m[15] = 1.0;
  5425. result.m[0] = c;
  5426. result.m[2] = -s;
  5427. result.m[8] = s;
  5428. result.m[10] = c;
  5429. result.m[1] = 0.0;
  5430. result.m[3] = 0.0;
  5431. result.m[4] = 0.0;
  5432. result.m[6] = 0.0;
  5433. result.m[7] = 0.0;
  5434. result.m[9] = 0.0;
  5435. result.m[11] = 0.0;
  5436. result.m[12] = 0.0;
  5437. result.m[13] = 0.0;
  5438. result.m[14] = 0.0;
  5439. result._markAsUpdated();
  5440. };
  5441. /**
  5442. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5443. */
  5444. Matrix.RotationZ = function (angle) {
  5445. var result = new Matrix();
  5446. Matrix.RotationZToRef(angle, result);
  5447. return result;
  5448. };
  5449. /**
  5450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5451. */
  5452. Matrix.RotationZToRef = function (angle, result) {
  5453. var s = Math.sin(angle);
  5454. var c = Math.cos(angle);
  5455. result.m[10] = 1.0;
  5456. result.m[15] = 1.0;
  5457. result.m[0] = c;
  5458. result.m[1] = s;
  5459. result.m[4] = -s;
  5460. result.m[5] = c;
  5461. result.m[2] = 0.0;
  5462. result.m[3] = 0.0;
  5463. result.m[6] = 0.0;
  5464. result.m[7] = 0.0;
  5465. result.m[8] = 0.0;
  5466. result.m[9] = 0.0;
  5467. result.m[11] = 0.0;
  5468. result.m[12] = 0.0;
  5469. result.m[13] = 0.0;
  5470. result.m[14] = 0.0;
  5471. result._markAsUpdated();
  5472. };
  5473. /**
  5474. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5475. */
  5476. Matrix.RotationAxis = function (axis, angle) {
  5477. var result = Matrix.Zero();
  5478. Matrix.RotationAxisToRef(axis, angle, result);
  5479. return result;
  5480. };
  5481. /**
  5482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5483. */
  5484. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5485. var s = Math.sin(-angle);
  5486. var c = Math.cos(-angle);
  5487. var c1 = 1 - c;
  5488. axis.normalize();
  5489. result.m[0] = (axis.x * axis.x) * c1 + c;
  5490. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5491. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5492. result.m[3] = 0.0;
  5493. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5494. result.m[5] = (axis.y * axis.y) * c1 + c;
  5495. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5496. result.m[7] = 0.0;
  5497. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5498. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5499. result.m[10] = (axis.z * axis.z) * c1 + c;
  5500. result.m[11] = 0.0;
  5501. result.m[15] = 1.0;
  5502. result._markAsUpdated();
  5503. };
  5504. /**
  5505. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5506. */
  5507. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5508. var result = new Matrix();
  5509. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5510. return result;
  5511. };
  5512. /**
  5513. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5514. */
  5515. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5516. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5517. this._tempQuaternion.toRotationMatrix(result);
  5518. };
  5519. /**
  5520. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5521. */
  5522. Matrix.Scaling = function (x, y, z) {
  5523. var result = Matrix.Zero();
  5524. Matrix.ScalingToRef(x, y, z, result);
  5525. return result;
  5526. };
  5527. /**
  5528. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5529. */
  5530. Matrix.ScalingToRef = function (x, y, z, result) {
  5531. result.m[0] = x;
  5532. result.m[1] = 0.0;
  5533. result.m[2] = 0.0;
  5534. result.m[3] = 0.0;
  5535. result.m[4] = 0.0;
  5536. result.m[5] = y;
  5537. result.m[6] = 0.0;
  5538. result.m[7] = 0.0;
  5539. result.m[8] = 0.0;
  5540. result.m[9] = 0.0;
  5541. result.m[10] = z;
  5542. result.m[11] = 0.0;
  5543. result.m[12] = 0.0;
  5544. result.m[13] = 0.0;
  5545. result.m[14] = 0.0;
  5546. result.m[15] = 1.0;
  5547. result._markAsUpdated();
  5548. };
  5549. /**
  5550. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5551. */
  5552. Matrix.Translation = function (x, y, z) {
  5553. var result = Matrix.Identity();
  5554. Matrix.TranslationToRef(x, y, z, result);
  5555. return result;
  5556. };
  5557. /**
  5558. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5559. */
  5560. Matrix.TranslationToRef = function (x, y, z, result) {
  5561. 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);
  5562. };
  5563. /**
  5564. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5565. * @param startValue defines the start value
  5566. * @param endValue defines the end value
  5567. * @param gradient defines the gradient factor
  5568. * @returns the new matrix
  5569. */
  5570. Matrix.Lerp = function (startValue, endValue, gradient) {
  5571. var result = Matrix.Zero();
  5572. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5573. return result;
  5574. };
  5575. /**
  5576. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5577. * @param startValue defines the start value
  5578. * @param endValue defines the end value
  5579. * @param gradient defines the gradient factor
  5580. * @param result defines the Matrix object where to store data
  5581. */
  5582. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5583. for (var index = 0; index < 16; index++) {
  5584. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5585. }
  5586. result._markAsUpdated();
  5587. };
  5588. /**
  5589. * Returns a new Matrix whose values are computed by :
  5590. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5591. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5592. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5593. */
  5594. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5595. var startScale = new Vector3(0, 0, 0);
  5596. var startRotation = new Quaternion();
  5597. var startTranslation = new Vector3(0, 0, 0);
  5598. startValue.decompose(startScale, startRotation, startTranslation);
  5599. var endScale = new Vector3(0, 0, 0);
  5600. var endRotation = new Quaternion();
  5601. var endTranslation = new Vector3(0, 0, 0);
  5602. endValue.decompose(endScale, endRotation, endTranslation);
  5603. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5604. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5605. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5606. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5607. };
  5608. /**
  5609. * 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".
  5610. * This methods works for a Left-Handed system.
  5611. */
  5612. Matrix.LookAtLH = function (eye, target, up) {
  5613. var result = Matrix.Zero();
  5614. Matrix.LookAtLHToRef(eye, target, up, result);
  5615. return result;
  5616. };
  5617. /**
  5618. * 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".
  5619. * This methods works for a Left-Handed system.
  5620. */
  5621. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5622. // Z axis
  5623. target.subtractToRef(eye, this._zAxis);
  5624. this._zAxis.normalize();
  5625. // X axis
  5626. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5627. if (this._xAxis.lengthSquared() === 0) {
  5628. this._xAxis.x = 1.0;
  5629. }
  5630. else {
  5631. this._xAxis.normalize();
  5632. }
  5633. // Y axis
  5634. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5635. this._yAxis.normalize();
  5636. // Eye angles
  5637. var ex = -Vector3.Dot(this._xAxis, eye);
  5638. var ey = -Vector3.Dot(this._yAxis, eye);
  5639. var ez = -Vector3.Dot(this._zAxis, eye);
  5640. 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);
  5641. };
  5642. /**
  5643. * 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".
  5644. * This methods works for a Right-Handed system.
  5645. */
  5646. Matrix.LookAtRH = function (eye, target, up) {
  5647. var result = Matrix.Zero();
  5648. Matrix.LookAtRHToRef(eye, target, up, result);
  5649. return result;
  5650. };
  5651. /**
  5652. * 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".
  5653. * This methods works for a Left-Handed system.
  5654. */
  5655. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5656. // Z axis
  5657. eye.subtractToRef(target, this._zAxis);
  5658. this._zAxis.normalize();
  5659. // X axis
  5660. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5661. if (this._xAxis.lengthSquared() === 0) {
  5662. this._xAxis.x = 1.0;
  5663. }
  5664. else {
  5665. this._xAxis.normalize();
  5666. }
  5667. // Y axis
  5668. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5669. this._yAxis.normalize();
  5670. // Eye angles
  5671. var ex = -Vector3.Dot(this._xAxis, eye);
  5672. var ey = -Vector3.Dot(this._yAxis, eye);
  5673. var ez = -Vector3.Dot(this._zAxis, eye);
  5674. 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);
  5675. };
  5676. /**
  5677. * 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.
  5678. */
  5679. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5680. var matrix = Matrix.Zero();
  5681. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5682. return matrix;
  5683. };
  5684. /**
  5685. * 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.
  5686. */
  5687. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5688. var n = znear;
  5689. var f = zfar;
  5690. var a = 2.0 / width;
  5691. var b = 2.0 / height;
  5692. var c = 2.0 / (f - n);
  5693. var d = -(f + n) / (f - n);
  5694. 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);
  5695. };
  5696. /**
  5697. * 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.
  5698. */
  5699. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5700. var matrix = Matrix.Zero();
  5701. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5702. return matrix;
  5703. };
  5704. /**
  5705. * 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.
  5706. */
  5707. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5708. var n = znear;
  5709. var f = zfar;
  5710. var a = 2.0 / (right - left);
  5711. var b = 2.0 / (top - bottom);
  5712. var c = 2.0 / (f - n);
  5713. var d = -(f + n) / (f - n);
  5714. var i0 = (left + right) / (left - right);
  5715. var i1 = (top + bottom) / (bottom - top);
  5716. 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);
  5717. };
  5718. /**
  5719. * 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.
  5720. */
  5721. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5722. var matrix = Matrix.Zero();
  5723. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5724. return matrix;
  5725. };
  5726. /**
  5727. * 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.
  5728. */
  5729. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5730. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5731. result.m[10] *= -1.0;
  5732. };
  5733. /**
  5734. * 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.
  5735. */
  5736. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5737. var matrix = Matrix.Zero();
  5738. var n = znear;
  5739. var f = zfar;
  5740. var a = 2.0 * n / width;
  5741. var b = 2.0 * n / height;
  5742. var c = (f + n) / (f - n);
  5743. var d = -2.0 * f * n / (f - n);
  5744. 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);
  5745. return matrix;
  5746. };
  5747. /**
  5748. * 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.
  5749. */
  5750. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5751. var matrix = Matrix.Zero();
  5752. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5753. return matrix;
  5754. };
  5755. /**
  5756. * 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.
  5757. */
  5758. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5759. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5760. var n = znear;
  5761. var f = zfar;
  5762. var t = 1.0 / (Math.tan(fov * 0.5));
  5763. var a = isVerticalFovFixed ? (t / aspect) : t;
  5764. var b = isVerticalFovFixed ? t : (t * aspect);
  5765. var c = (f + n) / (f - n);
  5766. var d = -2.0 * f * n / (f - n);
  5767. 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);
  5768. };
  5769. /**
  5770. * 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.
  5771. */
  5772. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5773. var matrix = Matrix.Zero();
  5774. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5775. return matrix;
  5776. };
  5777. /**
  5778. * 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.
  5779. */
  5780. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5781. //alternatively this could be expressed as:
  5782. // m = PerspectiveFovLHToRef
  5783. // m[10] *= -1.0;
  5784. // m[11] *= -1.0;
  5785. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5786. var n = znear;
  5787. var f = zfar;
  5788. var t = 1.0 / (Math.tan(fov * 0.5));
  5789. var a = isVerticalFovFixed ? (t / aspect) : t;
  5790. var b = isVerticalFovFixed ? t : (t * aspect);
  5791. var c = -(f + n) / (f - n);
  5792. var d = -2 * f * n / (f - n);
  5793. 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);
  5794. };
  5795. /**
  5796. * 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.
  5797. */
  5798. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5799. if (rightHanded === void 0) { rightHanded = false; }
  5800. var rightHandedFactor = rightHanded ? -1 : 1;
  5801. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5802. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5803. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5804. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5805. var xScale = 2.0 / (leftTan + rightTan);
  5806. var yScale = 2.0 / (upTan + downTan);
  5807. result.m[0] = xScale;
  5808. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5809. result.m[5] = yScale;
  5810. result.m[6] = result.m[7] = 0.0;
  5811. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5812. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5813. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5814. result.m[10] = -zfar / (znear - zfar);
  5815. result.m[11] = 1.0 * rightHandedFactor;
  5816. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5817. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5818. // result.m[14] = (znear * zfar) / (znear - zfar);
  5819. result._markAsUpdated();
  5820. };
  5821. /**
  5822. * Returns the final transformation matrix : world * view * projection * viewport
  5823. */
  5824. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5825. var cw = viewport.width;
  5826. var ch = viewport.height;
  5827. var cx = viewport.x;
  5828. var cy = viewport.y;
  5829. 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);
  5830. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5831. };
  5832. /**
  5833. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5834. */
  5835. Matrix.GetAsMatrix2x2 = function (matrix) {
  5836. return new Float32Array([
  5837. matrix.m[0], matrix.m[1],
  5838. matrix.m[4], matrix.m[5]
  5839. ]);
  5840. };
  5841. /**
  5842. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5843. */
  5844. Matrix.GetAsMatrix3x3 = function (matrix) {
  5845. return new Float32Array([
  5846. matrix.m[0], matrix.m[1], matrix.m[2],
  5847. matrix.m[4], matrix.m[5], matrix.m[6],
  5848. matrix.m[8], matrix.m[9], matrix.m[10]
  5849. ]);
  5850. };
  5851. /**
  5852. * Compute the transpose of the passed Matrix.
  5853. * Returns a new Matrix.
  5854. */
  5855. Matrix.Transpose = function (matrix) {
  5856. var result = new Matrix();
  5857. Matrix.TransposeToRef(matrix, result);
  5858. return result;
  5859. };
  5860. /**
  5861. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5862. */
  5863. Matrix.TransposeToRef = function (matrix, result) {
  5864. result.m[0] = matrix.m[0];
  5865. result.m[1] = matrix.m[4];
  5866. result.m[2] = matrix.m[8];
  5867. result.m[3] = matrix.m[12];
  5868. result.m[4] = matrix.m[1];
  5869. result.m[5] = matrix.m[5];
  5870. result.m[6] = matrix.m[9];
  5871. result.m[7] = matrix.m[13];
  5872. result.m[8] = matrix.m[2];
  5873. result.m[9] = matrix.m[6];
  5874. result.m[10] = matrix.m[10];
  5875. result.m[11] = matrix.m[14];
  5876. result.m[12] = matrix.m[3];
  5877. result.m[13] = matrix.m[7];
  5878. result.m[14] = matrix.m[11];
  5879. result.m[15] = matrix.m[15];
  5880. };
  5881. /**
  5882. * Returns a new Matrix as the reflection matrix across the passed plane.
  5883. */
  5884. Matrix.Reflection = function (plane) {
  5885. var matrix = new Matrix();
  5886. Matrix.ReflectionToRef(plane, matrix);
  5887. return matrix;
  5888. };
  5889. /**
  5890. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5891. */
  5892. Matrix.ReflectionToRef = function (plane, result) {
  5893. plane.normalize();
  5894. var x = plane.normal.x;
  5895. var y = plane.normal.y;
  5896. var z = plane.normal.z;
  5897. var temp = -2 * x;
  5898. var temp2 = -2 * y;
  5899. var temp3 = -2 * z;
  5900. result.m[0] = (temp * x) + 1;
  5901. result.m[1] = temp2 * x;
  5902. result.m[2] = temp3 * x;
  5903. result.m[3] = 0.0;
  5904. result.m[4] = temp * y;
  5905. result.m[5] = (temp2 * y) + 1;
  5906. result.m[6] = temp3 * y;
  5907. result.m[7] = 0.0;
  5908. result.m[8] = temp * z;
  5909. result.m[9] = temp2 * z;
  5910. result.m[10] = (temp3 * z) + 1;
  5911. result.m[11] = 0.0;
  5912. result.m[12] = temp * plane.d;
  5913. result.m[13] = temp2 * plane.d;
  5914. result.m[14] = temp3 * plane.d;
  5915. result.m[15] = 1.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5920. */
  5921. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5922. result.m[0] = xaxis.x;
  5923. result.m[1] = xaxis.y;
  5924. result.m[2] = xaxis.z;
  5925. result.m[3] = 0.0;
  5926. result.m[4] = yaxis.x;
  5927. result.m[5] = yaxis.y;
  5928. result.m[6] = yaxis.z;
  5929. result.m[7] = 0.0;
  5930. result.m[8] = zaxis.x;
  5931. result.m[9] = zaxis.y;
  5932. result.m[10] = zaxis.z;
  5933. result.m[11] = 0.0;
  5934. result.m[12] = 0.0;
  5935. result.m[13] = 0.0;
  5936. result.m[14] = 0.0;
  5937. result.m[15] = 1.0;
  5938. result._markAsUpdated();
  5939. };
  5940. /**
  5941. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5942. */
  5943. Matrix.FromQuaternionToRef = function (quat, result) {
  5944. var xx = quat.x * quat.x;
  5945. var yy = quat.y * quat.y;
  5946. var zz = quat.z * quat.z;
  5947. var xy = quat.x * quat.y;
  5948. var zw = quat.z * quat.w;
  5949. var zx = quat.z * quat.x;
  5950. var yw = quat.y * quat.w;
  5951. var yz = quat.y * quat.z;
  5952. var xw = quat.x * quat.w;
  5953. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5954. result.m[1] = 2.0 * (xy + zw);
  5955. result.m[2] = 2.0 * (zx - yw);
  5956. result.m[3] = 0.0;
  5957. result.m[4] = 2.0 * (xy - zw);
  5958. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5959. result.m[6] = 2.0 * (yz + xw);
  5960. result.m[7] = 0.0;
  5961. result.m[8] = 2.0 * (zx + yw);
  5962. result.m[9] = 2.0 * (yz - xw);
  5963. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5964. result.m[11] = 0.0;
  5965. result.m[12] = 0.0;
  5966. result.m[13] = 0.0;
  5967. result.m[14] = 0.0;
  5968. result.m[15] = 1.0;
  5969. result._markAsUpdated();
  5970. };
  5971. Matrix._tempQuaternion = new Quaternion();
  5972. Matrix._xAxis = Vector3.Zero();
  5973. Matrix._yAxis = Vector3.Zero();
  5974. Matrix._zAxis = Vector3.Zero();
  5975. Matrix._updateFlagSeed = 0;
  5976. Matrix._identityReadOnly = Matrix.Identity();
  5977. return Matrix;
  5978. }());
  5979. BABYLON.Matrix = Matrix;
  5980. var Plane = /** @class */ (function () {
  5981. /**
  5982. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5983. */
  5984. function Plane(a, b, c, d) {
  5985. this.normal = new Vector3(a, b, c);
  5986. this.d = d;
  5987. }
  5988. /**
  5989. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5990. */
  5991. Plane.prototype.asArray = function () {
  5992. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5993. };
  5994. // Methods
  5995. /**
  5996. * Returns a new plane copied from the current Plane.
  5997. */
  5998. Plane.prototype.clone = function () {
  5999. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6000. };
  6001. /**
  6002. * Returns the string "Plane".
  6003. */
  6004. Plane.prototype.getClassName = function () {
  6005. return "Plane";
  6006. };
  6007. /**
  6008. * Returns the Plane hash code.
  6009. */
  6010. Plane.prototype.getHashCode = function () {
  6011. var hash = this.normal.getHashCode();
  6012. hash = (hash * 397) ^ (this.d || 0);
  6013. return hash;
  6014. };
  6015. /**
  6016. * Normalize the current Plane in place.
  6017. * Returns the updated Plane.
  6018. */
  6019. Plane.prototype.normalize = function () {
  6020. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6021. var magnitude = 0.0;
  6022. if (norm !== 0) {
  6023. magnitude = 1.0 / norm;
  6024. }
  6025. this.normal.x *= magnitude;
  6026. this.normal.y *= magnitude;
  6027. this.normal.z *= magnitude;
  6028. this.d *= magnitude;
  6029. return this;
  6030. };
  6031. /**
  6032. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6033. */
  6034. Plane.prototype.transform = function (transformation) {
  6035. var transposedMatrix = Matrix.Transpose(transformation);
  6036. var x = this.normal.x;
  6037. var y = this.normal.y;
  6038. var z = this.normal.z;
  6039. var d = this.d;
  6040. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6041. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6042. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6043. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6044. return new Plane(normalX, normalY, normalZ, finalD);
  6045. };
  6046. /**
  6047. * Returns the dot product (float) of the point coordinates and the plane normal.
  6048. */
  6049. Plane.prototype.dotCoordinate = function (point) {
  6050. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6051. };
  6052. /**
  6053. * Updates the current Plane from the plane defined by the three passed points.
  6054. * Returns the updated Plane.
  6055. */
  6056. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6057. var x1 = point2.x - point1.x;
  6058. var y1 = point2.y - point1.y;
  6059. var z1 = point2.z - point1.z;
  6060. var x2 = point3.x - point1.x;
  6061. var y2 = point3.y - point1.y;
  6062. var z2 = point3.z - point1.z;
  6063. var yz = (y1 * z2) - (z1 * y2);
  6064. var xz = (z1 * x2) - (x1 * z2);
  6065. var xy = (x1 * y2) - (y1 * x2);
  6066. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6067. var invPyth;
  6068. if (pyth !== 0) {
  6069. invPyth = 1.0 / pyth;
  6070. }
  6071. else {
  6072. invPyth = 0.0;
  6073. }
  6074. this.normal.x = yz * invPyth;
  6075. this.normal.y = xz * invPyth;
  6076. this.normal.z = xy * invPyth;
  6077. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6078. return this;
  6079. };
  6080. /**
  6081. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6082. */
  6083. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6084. var dot = Vector3.Dot(this.normal, direction);
  6085. return (dot <= epsilon);
  6086. };
  6087. /**
  6088. * Returns the signed distance (float) from the passed point to the Plane.
  6089. */
  6090. Plane.prototype.signedDistanceTo = function (point) {
  6091. return Vector3.Dot(point, this.normal) + this.d;
  6092. };
  6093. // Statics
  6094. /**
  6095. * Returns a new Plane from the passed array.
  6096. */
  6097. Plane.FromArray = function (array) {
  6098. return new Plane(array[0], array[1], array[2], array[3]);
  6099. };
  6100. /**
  6101. * Returns a new Plane defined by the three passed points.
  6102. */
  6103. Plane.FromPoints = function (point1, point2, point3) {
  6104. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6105. result.copyFromPoints(point1, point2, point3);
  6106. return result;
  6107. };
  6108. /**
  6109. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6110. * Note : the vector "normal" is updated because normalized.
  6111. */
  6112. Plane.FromPositionAndNormal = function (origin, normal) {
  6113. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6114. normal.normalize();
  6115. result.normal = normal;
  6116. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6117. return result;
  6118. };
  6119. /**
  6120. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6121. */
  6122. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6123. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6124. return Vector3.Dot(point, normal) + d;
  6125. };
  6126. return Plane;
  6127. }());
  6128. BABYLON.Plane = Plane;
  6129. var Viewport = /** @class */ (function () {
  6130. /**
  6131. * Creates a Viewport object located at (x, y) and sized (width, height).
  6132. */
  6133. function Viewport(x, y, width, height) {
  6134. this.x = x;
  6135. this.y = y;
  6136. this.width = width;
  6137. this.height = height;
  6138. }
  6139. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6140. if (renderWidthOrEngine.getRenderWidth) {
  6141. var engine = renderWidthOrEngine;
  6142. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6143. }
  6144. var renderWidth = renderWidthOrEngine;
  6145. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6146. };
  6147. /**
  6148. * Returns a new Viewport copied from the current one.
  6149. */
  6150. Viewport.prototype.clone = function () {
  6151. return new Viewport(this.x, this.y, this.width, this.height);
  6152. };
  6153. return Viewport;
  6154. }());
  6155. BABYLON.Viewport = Viewport;
  6156. var Frustum = /** @class */ (function () {
  6157. function Frustum() {
  6158. }
  6159. /**
  6160. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6161. */
  6162. Frustum.GetPlanes = function (transform) {
  6163. var frustumPlanes = [];
  6164. for (var index = 0; index < 6; index++) {
  6165. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6166. }
  6167. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6168. return frustumPlanes;
  6169. };
  6170. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6171. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6172. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6173. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6174. frustumPlane.d = transform.m[15] + transform.m[14];
  6175. frustumPlane.normalize();
  6176. };
  6177. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6178. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6179. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6180. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6181. frustumPlane.d = transform.m[15] - transform.m[14];
  6182. frustumPlane.normalize();
  6183. };
  6184. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6185. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6186. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6187. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6188. frustumPlane.d = transform.m[15] + transform.m[12];
  6189. frustumPlane.normalize();
  6190. };
  6191. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6192. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6193. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6194. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6195. frustumPlane.d = transform.m[15] - transform.m[12];
  6196. frustumPlane.normalize();
  6197. };
  6198. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6199. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6200. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6201. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6202. frustumPlane.d = transform.m[15] - transform.m[13];
  6203. frustumPlane.normalize();
  6204. };
  6205. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6206. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6207. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6208. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6209. frustumPlane.d = transform.m[15] + transform.m[13];
  6210. frustumPlane.normalize();
  6211. };
  6212. /**
  6213. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6214. */
  6215. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6216. // Near
  6217. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6218. // Far
  6219. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6220. // Left
  6221. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6222. // Right
  6223. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6224. // Top
  6225. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6226. // Bottom
  6227. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6228. };
  6229. return Frustum;
  6230. }());
  6231. BABYLON.Frustum = Frustum;
  6232. var Space;
  6233. (function (Space) {
  6234. Space[Space["LOCAL"] = 0] = "LOCAL";
  6235. Space[Space["WORLD"] = 1] = "WORLD";
  6236. Space[Space["BONE"] = 2] = "BONE";
  6237. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6238. var Axis = /** @class */ (function () {
  6239. function Axis() {
  6240. }
  6241. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6242. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6243. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6244. return Axis;
  6245. }());
  6246. BABYLON.Axis = Axis;
  6247. ;
  6248. var BezierCurve = /** @class */ (function () {
  6249. function BezierCurve() {
  6250. }
  6251. /**
  6252. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6253. */
  6254. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6255. // Extract X (which is equal to time here)
  6256. var f0 = 1 - 3 * x2 + 3 * x1;
  6257. var f1 = 3 * x2 - 6 * x1;
  6258. var f2 = 3 * x1;
  6259. var refinedT = t;
  6260. for (var i = 0; i < 5; i++) {
  6261. var refinedT2 = refinedT * refinedT;
  6262. var refinedT3 = refinedT2 * refinedT;
  6263. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6264. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6265. refinedT -= (x - t) * slope;
  6266. refinedT = Math.min(1, Math.max(0, refinedT));
  6267. }
  6268. // Resolve cubic bezier for the given x
  6269. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6270. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6271. Math.pow(refinedT, 3);
  6272. };
  6273. return BezierCurve;
  6274. }());
  6275. BABYLON.BezierCurve = BezierCurve;
  6276. var Orientation;
  6277. (function (Orientation) {
  6278. Orientation[Orientation["CW"] = 0] = "CW";
  6279. Orientation[Orientation["CCW"] = 1] = "CCW";
  6280. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6281. var Angle = /** @class */ (function () {
  6282. /**
  6283. * Creates an Angle object of "radians" radians (float).
  6284. */
  6285. function Angle(radians) {
  6286. var _this = this;
  6287. /**
  6288. * Returns the Angle value in degrees (float).
  6289. */
  6290. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6291. /**
  6292. * Returns the Angle value in radians (float).
  6293. */
  6294. this.radians = function () { return _this._radians; };
  6295. this._radians = radians;
  6296. if (this._radians < 0.0)
  6297. this._radians += (2.0 * Math.PI);
  6298. }
  6299. /**
  6300. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6301. */
  6302. Angle.BetweenTwoPoints = function (a, b) {
  6303. var delta = b.subtract(a);
  6304. var theta = Math.atan2(delta.y, delta.x);
  6305. return new Angle(theta);
  6306. };
  6307. /**
  6308. * Returns a new Angle object from the passed float in radians.
  6309. */
  6310. Angle.FromRadians = function (radians) {
  6311. return new Angle(radians);
  6312. };
  6313. /**
  6314. * Returns a new Angle object from the passed float in degrees.
  6315. */
  6316. Angle.FromDegrees = function (degrees) {
  6317. return new Angle(degrees * Math.PI / 180.0);
  6318. };
  6319. return Angle;
  6320. }());
  6321. BABYLON.Angle = Angle;
  6322. var Arc2 = /** @class */ (function () {
  6323. /**
  6324. * Creates an Arc object from the three passed points : start, middle and end.
  6325. */
  6326. function Arc2(startPoint, midPoint, endPoint) {
  6327. this.startPoint = startPoint;
  6328. this.midPoint = midPoint;
  6329. this.endPoint = endPoint;
  6330. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6331. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6332. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6333. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6334. 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);
  6335. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6336. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6337. var a1 = this.startAngle.degrees();
  6338. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6339. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6340. // angles correction
  6341. if (a2 - a1 > +180.0)
  6342. a2 -= 360.0;
  6343. if (a2 - a1 < -180.0)
  6344. a2 += 360.0;
  6345. if (a3 - a2 > +180.0)
  6346. a3 -= 360.0;
  6347. if (a3 - a2 < -180.0)
  6348. a3 += 360.0;
  6349. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6350. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6351. }
  6352. return Arc2;
  6353. }());
  6354. BABYLON.Arc2 = Arc2;
  6355. var Path2 = /** @class */ (function () {
  6356. /**
  6357. * Creates a Path2 object from the starting 2D coordinates x and y.
  6358. */
  6359. function Path2(x, y) {
  6360. this._points = new Array();
  6361. this._length = 0.0;
  6362. this.closed = false;
  6363. this._points.push(new Vector2(x, y));
  6364. }
  6365. /**
  6366. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6367. * Returns the updated Path2.
  6368. */
  6369. Path2.prototype.addLineTo = function (x, y) {
  6370. if (this.closed) {
  6371. return this;
  6372. }
  6373. var newPoint = new Vector2(x, y);
  6374. var previousPoint = this._points[this._points.length - 1];
  6375. this._points.push(newPoint);
  6376. this._length += newPoint.subtract(previousPoint).length();
  6377. return this;
  6378. };
  6379. /**
  6380. * 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.
  6381. * Returns the updated Path2.
  6382. */
  6383. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6384. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6385. if (this.closed) {
  6386. return this;
  6387. }
  6388. var startPoint = this._points[this._points.length - 1];
  6389. var midPoint = new Vector2(midX, midY);
  6390. var endPoint = new Vector2(endX, endY);
  6391. var arc = new Arc2(startPoint, midPoint, endPoint);
  6392. var increment = arc.angle.radians() / numberOfSegments;
  6393. if (arc.orientation === Orientation.CW)
  6394. increment *= -1;
  6395. var currentAngle = arc.startAngle.radians() + increment;
  6396. for (var i = 0; i < numberOfSegments; i++) {
  6397. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6398. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6399. this.addLineTo(x, y);
  6400. currentAngle += increment;
  6401. }
  6402. return this;
  6403. };
  6404. /**
  6405. * Closes the Path2.
  6406. * Returns the Path2.
  6407. */
  6408. Path2.prototype.close = function () {
  6409. this.closed = true;
  6410. return this;
  6411. };
  6412. /**
  6413. * Returns the Path2 total length (float).
  6414. */
  6415. Path2.prototype.length = function () {
  6416. var result = this._length;
  6417. if (!this.closed) {
  6418. var lastPoint = this._points[this._points.length - 1];
  6419. var firstPoint = this._points[0];
  6420. result += (firstPoint.subtract(lastPoint).length());
  6421. }
  6422. return result;
  6423. };
  6424. /**
  6425. * Returns the Path2 internal array of points.
  6426. */
  6427. Path2.prototype.getPoints = function () {
  6428. return this._points;
  6429. };
  6430. /**
  6431. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6432. */
  6433. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6434. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6435. return Vector2.Zero();
  6436. }
  6437. var lengthPosition = normalizedLengthPosition * this.length();
  6438. var previousOffset = 0;
  6439. for (var i = 0; i < this._points.length; i++) {
  6440. var j = (i + 1) % this._points.length;
  6441. var a = this._points[i];
  6442. var b = this._points[j];
  6443. var bToA = b.subtract(a);
  6444. var nextOffset = (bToA.length() + previousOffset);
  6445. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6446. var dir = bToA.normalize();
  6447. var localOffset = lengthPosition - previousOffset;
  6448. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6449. }
  6450. previousOffset = nextOffset;
  6451. }
  6452. return Vector2.Zero();
  6453. };
  6454. /**
  6455. * Returns a new Path2 starting at the coordinates (x, y).
  6456. */
  6457. Path2.StartingAt = function (x, y) {
  6458. return new Path2(x, y);
  6459. };
  6460. return Path2;
  6461. }());
  6462. BABYLON.Path2 = Path2;
  6463. var Path3D = /** @class */ (function () {
  6464. /**
  6465. * new Path3D(path, normal, raw)
  6466. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6467. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6468. * path : an array of Vector3, the curve axis of the Path3D
  6469. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6470. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6471. */
  6472. function Path3D(path, firstNormal, raw) {
  6473. if (firstNormal === void 0) { firstNormal = null; }
  6474. this.path = path;
  6475. this._curve = new Array();
  6476. this._distances = new Array();
  6477. this._tangents = new Array();
  6478. this._normals = new Array();
  6479. this._binormals = new Array();
  6480. for (var p = 0; p < path.length; p++) {
  6481. this._curve[p] = path[p].clone(); // hard copy
  6482. }
  6483. this._raw = raw || false;
  6484. this._compute(firstNormal);
  6485. }
  6486. /**
  6487. * Returns the Path3D array of successive Vector3 designing its curve.
  6488. */
  6489. Path3D.prototype.getCurve = function () {
  6490. return this._curve;
  6491. };
  6492. /**
  6493. * Returns an array populated with tangent vectors on each Path3D curve point.
  6494. */
  6495. Path3D.prototype.getTangents = function () {
  6496. return this._tangents;
  6497. };
  6498. /**
  6499. * Returns an array populated with normal vectors on each Path3D curve point.
  6500. */
  6501. Path3D.prototype.getNormals = function () {
  6502. return this._normals;
  6503. };
  6504. /**
  6505. * Returns an array populated with binormal vectors on each Path3D curve point.
  6506. */
  6507. Path3D.prototype.getBinormals = function () {
  6508. return this._binormals;
  6509. };
  6510. /**
  6511. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6512. */
  6513. Path3D.prototype.getDistances = function () {
  6514. return this._distances;
  6515. };
  6516. /**
  6517. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6518. * Returns the same object updated.
  6519. */
  6520. Path3D.prototype.update = function (path, firstNormal) {
  6521. if (firstNormal === void 0) { firstNormal = null; }
  6522. for (var p = 0; p < path.length; p++) {
  6523. this._curve[p].x = path[p].x;
  6524. this._curve[p].y = path[p].y;
  6525. this._curve[p].z = path[p].z;
  6526. }
  6527. this._compute(firstNormal);
  6528. return this;
  6529. };
  6530. // private function compute() : computes tangents, normals and binormals
  6531. Path3D.prototype._compute = function (firstNormal) {
  6532. var l = this._curve.length;
  6533. // first and last tangents
  6534. this._tangents[0] = this._getFirstNonNullVector(0);
  6535. if (!this._raw) {
  6536. this._tangents[0].normalize();
  6537. }
  6538. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6539. if (!this._raw) {
  6540. this._tangents[l - 1].normalize();
  6541. }
  6542. // normals and binormals at first point : arbitrary vector with _normalVector()
  6543. var tg0 = this._tangents[0];
  6544. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6545. this._normals[0] = pp0;
  6546. if (!this._raw) {
  6547. this._normals[0].normalize();
  6548. }
  6549. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6550. if (!this._raw) {
  6551. this._binormals[0].normalize();
  6552. }
  6553. this._distances[0] = 0.0;
  6554. // normals and binormals : next points
  6555. var prev; // previous vector (segment)
  6556. var cur; // current vector (segment)
  6557. var curTang; // current tangent
  6558. // previous normal
  6559. var prevBinor; // previous binormal
  6560. for (var i = 1; i < l; i++) {
  6561. // tangents
  6562. prev = this._getLastNonNullVector(i);
  6563. if (i < l - 1) {
  6564. cur = this._getFirstNonNullVector(i);
  6565. this._tangents[i] = prev.add(cur);
  6566. this._tangents[i].normalize();
  6567. }
  6568. this._distances[i] = this._distances[i - 1] + prev.length();
  6569. // normals and binormals
  6570. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6571. curTang = this._tangents[i];
  6572. prevBinor = this._binormals[i - 1];
  6573. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6574. if (!this._raw) {
  6575. this._normals[i].normalize();
  6576. }
  6577. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6578. if (!this._raw) {
  6579. this._binormals[i].normalize();
  6580. }
  6581. }
  6582. };
  6583. // private function getFirstNonNullVector(index)
  6584. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6585. Path3D.prototype._getFirstNonNullVector = function (index) {
  6586. var i = 1;
  6587. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6588. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6589. i++;
  6590. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6591. }
  6592. return nNVector;
  6593. };
  6594. // private function getLastNonNullVector(index)
  6595. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6596. Path3D.prototype._getLastNonNullVector = function (index) {
  6597. var i = 1;
  6598. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6599. while (nLVector.length() === 0 && index > i + 1) {
  6600. i++;
  6601. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6602. }
  6603. return nLVector;
  6604. };
  6605. // private function normalVector(v0, vt, va) :
  6606. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6607. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6608. Path3D.prototype._normalVector = function (v0, vt, va) {
  6609. var normal0;
  6610. var tgl = vt.length();
  6611. if (tgl === 0.0) {
  6612. tgl = 1.0;
  6613. }
  6614. if (va === undefined || va === null) {
  6615. var point;
  6616. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6617. point = new Vector3(0.0, -1.0, 0.0);
  6618. }
  6619. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6620. point = new Vector3(1.0, 0.0, 0.0);
  6621. }
  6622. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6623. point = new Vector3(0.0, 0.0, 1.0);
  6624. }
  6625. else {
  6626. point = Vector3.Zero();
  6627. }
  6628. normal0 = Vector3.Cross(vt, point);
  6629. }
  6630. else {
  6631. normal0 = Vector3.Cross(vt, va);
  6632. Vector3.CrossToRef(normal0, vt, normal0);
  6633. }
  6634. normal0.normalize();
  6635. return normal0;
  6636. };
  6637. return Path3D;
  6638. }());
  6639. BABYLON.Path3D = Path3D;
  6640. var Curve3 = /** @class */ (function () {
  6641. /**
  6642. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6643. * A Curve3 is designed from a series of successive Vector3.
  6644. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6645. */
  6646. function Curve3(points) {
  6647. this._length = 0.0;
  6648. this._points = points;
  6649. this._length = this._computeLength(points);
  6650. }
  6651. /**
  6652. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6653. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6654. * @param v1 (Vector3) the control point
  6655. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6656. * @param nbPoints (integer) the wanted number of points in the curve
  6657. */
  6658. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6659. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6660. var bez = new Array();
  6661. var equation = function (t, val0, val1, val2) {
  6662. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6663. return res;
  6664. };
  6665. for (var i = 0; i <= nbPoints; i++) {
  6666. 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)));
  6667. }
  6668. return new Curve3(bez);
  6669. };
  6670. /**
  6671. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6672. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6673. * @param v1 (Vector3) the first control point
  6674. * @param v2 (Vector3) the second control point
  6675. * @param v3 (Vector3) the end point of the Cubic Bezier
  6676. * @param nbPoints (integer) the wanted number of points in the curve
  6677. */
  6678. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6679. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6680. var bez = new Array();
  6681. var equation = function (t, val0, val1, val2, val3) {
  6682. 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;
  6683. return res;
  6684. };
  6685. for (var i = 0; i <= nbPoints; i++) {
  6686. 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)));
  6687. }
  6688. return new Curve3(bez);
  6689. };
  6690. /**
  6691. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6692. * @param p1 (Vector3) the origin point of the Hermite Spline
  6693. * @param t1 (Vector3) the tangent vector at the origin point
  6694. * @param p2 (Vector3) the end point of the Hermite Spline
  6695. * @param t2 (Vector3) the tangent vector at the end point
  6696. * @param nbPoints (integer) the wanted number of points in the curve
  6697. */
  6698. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6699. var hermite = new Array();
  6700. var step = 1.0 / nbPoints;
  6701. for (var i = 0; i <= nbPoints; i++) {
  6702. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6703. }
  6704. return new Curve3(hermite);
  6705. };
  6706. /**
  6707. * Returns a Curve3 object along a CatmullRom Spline curve :
  6708. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6709. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6710. */
  6711. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6712. var totalPoints = new Array();
  6713. totalPoints.push(points[0].clone());
  6714. Array.prototype.push.apply(totalPoints, points);
  6715. totalPoints.push(points[points.length - 1].clone());
  6716. var catmullRom = new Array();
  6717. var step = 1.0 / nbPoints;
  6718. var amount = 0.0;
  6719. for (var i = 0; i < totalPoints.length - 3; i++) {
  6720. amount = 0;
  6721. for (var c = 0; c < nbPoints; c++) {
  6722. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6723. amount += step;
  6724. }
  6725. }
  6726. i--;
  6727. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6728. return new Curve3(catmullRom);
  6729. };
  6730. /**
  6731. * Returns the Curve3 stored array of successive Vector3
  6732. */
  6733. Curve3.prototype.getPoints = function () {
  6734. return this._points;
  6735. };
  6736. /**
  6737. * Returns the computed length (float) of the curve.
  6738. */
  6739. Curve3.prototype.length = function () {
  6740. return this._length;
  6741. };
  6742. /**
  6743. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6744. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6745. * curveA and curveB keep unchanged.
  6746. */
  6747. Curve3.prototype.continue = function (curve) {
  6748. var lastPoint = this._points[this._points.length - 1];
  6749. var continuedPoints = this._points.slice();
  6750. var curvePoints = curve.getPoints();
  6751. for (var i = 1; i < curvePoints.length; i++) {
  6752. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6753. }
  6754. var continuedCurve = new Curve3(continuedPoints);
  6755. return continuedCurve;
  6756. };
  6757. Curve3.prototype._computeLength = function (path) {
  6758. var l = 0;
  6759. for (var i = 1; i < path.length; i++) {
  6760. l += (path[i].subtract(path[i - 1])).length();
  6761. }
  6762. return l;
  6763. };
  6764. return Curve3;
  6765. }());
  6766. BABYLON.Curve3 = Curve3;
  6767. // Vertex formats
  6768. var PositionNormalVertex = /** @class */ (function () {
  6769. function PositionNormalVertex(position, normal) {
  6770. if (position === void 0) { position = Vector3.Zero(); }
  6771. if (normal === void 0) { normal = Vector3.Up(); }
  6772. this.position = position;
  6773. this.normal = normal;
  6774. }
  6775. PositionNormalVertex.prototype.clone = function () {
  6776. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6777. };
  6778. return PositionNormalVertex;
  6779. }());
  6780. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6781. var PositionNormalTextureVertex = /** @class */ (function () {
  6782. function PositionNormalTextureVertex(position, normal, uv) {
  6783. if (position === void 0) { position = Vector3.Zero(); }
  6784. if (normal === void 0) { normal = Vector3.Up(); }
  6785. if (uv === void 0) { uv = Vector2.Zero(); }
  6786. this.position = position;
  6787. this.normal = normal;
  6788. this.uv = uv;
  6789. }
  6790. PositionNormalTextureVertex.prototype.clone = function () {
  6791. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6792. };
  6793. return PositionNormalTextureVertex;
  6794. }());
  6795. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6796. // Temporary pre-allocated objects for engine internal use
  6797. // usage in any internal function :
  6798. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6799. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6800. var Tmp = /** @class */ (function () {
  6801. function Tmp() {
  6802. }
  6803. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6804. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6805. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6806. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6807. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6808. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6809. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6810. Matrix.Zero(), Matrix.Zero(),
  6811. Matrix.Zero(), Matrix.Zero(),
  6812. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6813. return Tmp;
  6814. }());
  6815. BABYLON.Tmp = Tmp;
  6816. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6817. var MathTmp = /** @class */ (function () {
  6818. function MathTmp() {
  6819. }
  6820. MathTmp.Vector3 = [Vector3.Zero()];
  6821. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6822. MathTmp.Quaternion = [Quaternion.Zero()];
  6823. return MathTmp;
  6824. }());
  6825. })(BABYLON || (BABYLON = {}));
  6826. //# sourceMappingURL=babylon.math.js.map
  6827. "use strict";
  6828. var BABYLON;
  6829. (function (BABYLON) {
  6830. var Scalar = /** @class */ (function () {
  6831. function Scalar() {
  6832. }
  6833. /**
  6834. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6835. */
  6836. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6837. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6838. var num = a - b;
  6839. return -epsilon <= num && num <= epsilon;
  6840. };
  6841. /**
  6842. * Returns a string : the upper case translation of the number i to hexadecimal.
  6843. */
  6844. Scalar.ToHex = function (i) {
  6845. var str = i.toString(16);
  6846. if (i <= 15) {
  6847. return ("0" + str).toUpperCase();
  6848. }
  6849. return str.toUpperCase();
  6850. };
  6851. /**
  6852. * Returns -1 if value is negative and +1 is value is positive.
  6853. * Returns the value itself if it's equal to zero.
  6854. */
  6855. Scalar.Sign = function (value) {
  6856. value = +value; // convert to a number
  6857. if (value === 0 || isNaN(value))
  6858. return value;
  6859. return value > 0 ? 1 : -1;
  6860. };
  6861. /**
  6862. * Returns the value itself if it's between min and max.
  6863. * Returns min if the value is lower than min.
  6864. * Returns max if the value is greater than max.
  6865. */
  6866. Scalar.Clamp = function (value, min, max) {
  6867. if (min === void 0) { min = 0; }
  6868. if (max === void 0) { max = 1; }
  6869. return Math.min(max, Math.max(min, value));
  6870. };
  6871. /**
  6872. * Returns the log2 of value.
  6873. */
  6874. Scalar.Log2 = function (value) {
  6875. return Math.log(value) * Math.LOG2E;
  6876. };
  6877. /**
  6878. * Loops the value, so that it is never larger than length and never smaller than 0.
  6879. *
  6880. * This is similar to the modulo operator but it works with floating point numbers.
  6881. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6882. * With t = 5 and length = 2.5, the result would be 0.0.
  6883. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6884. */
  6885. Scalar.Repeat = function (value, length) {
  6886. return value - Math.floor(value / length) * length;
  6887. };
  6888. /**
  6889. * Normalize the value between 0.0 and 1.0 using min and max values
  6890. */
  6891. Scalar.Normalize = function (value, min, max) {
  6892. return (value - min) / (max - min);
  6893. };
  6894. /**
  6895. * Denormalize the value from 0.0 and 1.0 using min and max values
  6896. */
  6897. Scalar.Denormalize = function (normalized, min, max) {
  6898. return (normalized * (max - min) + min);
  6899. };
  6900. /**
  6901. * Calculates the shortest difference between two given angles given in degrees.
  6902. */
  6903. Scalar.DeltaAngle = function (current, target) {
  6904. var num = Scalar.Repeat(target - current, 360.0);
  6905. if (num > 180.0) {
  6906. num -= 360.0;
  6907. }
  6908. return num;
  6909. };
  6910. /**
  6911. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6912. *
  6913. * The returned value will move back and forth between 0 and length
  6914. */
  6915. Scalar.PingPong = function (tx, length) {
  6916. var t = Scalar.Repeat(tx, length * 2.0);
  6917. return length - Math.abs(t - length);
  6918. };
  6919. /**
  6920. * Interpolates between min and max with smoothing at the limits.
  6921. *
  6922. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6923. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6924. */
  6925. Scalar.SmoothStep = function (from, to, tx) {
  6926. var t = Scalar.Clamp(tx);
  6927. t = -2.0 * t * t * t + 3.0 * t * t;
  6928. return to * t + from * (1.0 - t);
  6929. };
  6930. /**
  6931. * Moves a value current towards target.
  6932. *
  6933. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6934. * Negative values of maxDelta pushes the value away from target.
  6935. */
  6936. Scalar.MoveTowards = function (current, target, maxDelta) {
  6937. var result = 0;
  6938. if (Math.abs(target - current) <= maxDelta) {
  6939. result = target;
  6940. }
  6941. else {
  6942. result = current + Scalar.Sign(target - current) * maxDelta;
  6943. }
  6944. return result;
  6945. };
  6946. /**
  6947. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6948. *
  6949. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6950. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6951. */
  6952. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6953. var num = Scalar.DeltaAngle(current, target);
  6954. var result = 0;
  6955. if (-maxDelta < num && num < maxDelta) {
  6956. result = target;
  6957. }
  6958. else {
  6959. target = current + num;
  6960. result = Scalar.MoveTowards(current, target, maxDelta);
  6961. }
  6962. return result;
  6963. };
  6964. /**
  6965. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6966. */
  6967. Scalar.Lerp = function (start, end, amount) {
  6968. return start + ((end - start) * amount);
  6969. };
  6970. /**
  6971. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6972. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6973. */
  6974. Scalar.LerpAngle = function (start, end, amount) {
  6975. var num = Scalar.Repeat(end - start, 360.0);
  6976. if (num > 180.0) {
  6977. num -= 360.0;
  6978. }
  6979. return start + num * Scalar.Clamp(amount);
  6980. };
  6981. /**
  6982. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6983. */
  6984. Scalar.InverseLerp = function (a, b, value) {
  6985. var result = 0;
  6986. if (a != b) {
  6987. result = Scalar.Clamp((value - a) / (b - a));
  6988. }
  6989. else {
  6990. result = 0.0;
  6991. }
  6992. return result;
  6993. };
  6994. /**
  6995. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6996. */
  6997. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6998. var squared = amount * amount;
  6999. var cubed = amount * squared;
  7000. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7001. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7002. var part3 = (cubed - (2.0 * squared)) + amount;
  7003. var part4 = cubed - squared;
  7004. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7005. };
  7006. /**
  7007. * Returns a random float number between and min and max values
  7008. */
  7009. Scalar.RandomRange = function (min, max) {
  7010. if (min === max)
  7011. return min;
  7012. return ((Math.random() * (max - min)) + min);
  7013. };
  7014. /**
  7015. * This function returns percentage of a number in a given range.
  7016. *
  7017. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7018. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7019. */
  7020. Scalar.RangeToPercent = function (number, min, max) {
  7021. return ((number - min) / (max - min));
  7022. };
  7023. /**
  7024. * This function returns number that corresponds to the percentage in a given range.
  7025. *
  7026. * PercentToRange(0.34,0,100) will return 34.
  7027. */
  7028. Scalar.PercentToRange = function (percent, min, max) {
  7029. return ((max - min) * percent + min);
  7030. };
  7031. /**
  7032. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7033. * @param angle The angle to normalize in radian.
  7034. * @return The converted angle.
  7035. */
  7036. Scalar.NormalizeRadians = function (angle) {
  7037. // More precise but slower version kept for reference.
  7038. // angle = angle % Tools.TwoPi;
  7039. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7040. //if (angle > Math.PI) {
  7041. // angle -= Tools.TwoPi;
  7042. //}
  7043. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7044. return angle;
  7045. };
  7046. /**
  7047. * Two pi constants convenient for computation.
  7048. */
  7049. Scalar.TwoPi = Math.PI * 2;
  7050. return Scalar;
  7051. }());
  7052. BABYLON.Scalar = Scalar;
  7053. })(BABYLON || (BABYLON = {}));
  7054. //# sourceMappingURL=babylon.math.scalar.js.map
  7055. "use strict";
  7056. //# sourceMappingURL=babylon.mixins.js.map
  7057. "use strict";
  7058. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7059. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7060. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7061. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7062. //# sourceMappingURL=babylon.webgl2.js.map
  7063. "use strict";
  7064. var BABYLON;
  7065. (function (BABYLON) {
  7066. var __decoratorInitialStore = {};
  7067. var __mergedStore = {};
  7068. var _copySource = function (creationFunction, source, instanciate) {
  7069. var destination = creationFunction();
  7070. // Tags
  7071. if (BABYLON.Tags) {
  7072. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7073. }
  7074. var classStore = getMergedStore(destination);
  7075. // Properties
  7076. for (var property in classStore) {
  7077. var propertyDescriptor = classStore[property];
  7078. var sourceProperty = source[property];
  7079. var propertyType = propertyDescriptor.type;
  7080. if (sourceProperty !== undefined && sourceProperty !== null) {
  7081. switch (propertyType) {
  7082. case 0: // Value
  7083. case 6:// Mesh reference
  7084. destination[property] = sourceProperty;
  7085. break;
  7086. case 1:// Texture
  7087. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7088. break;
  7089. case 2: // Color3
  7090. case 3: // FresnelParameters
  7091. case 4: // Vector2
  7092. case 5: // Vector3
  7093. case 7: // Color Curves
  7094. case 10:// Quaternion
  7095. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7096. break;
  7097. }
  7098. }
  7099. }
  7100. return destination;
  7101. };
  7102. function getDirectStore(target) {
  7103. var classKey = target.getClassName();
  7104. if (!__decoratorInitialStore[classKey]) {
  7105. __decoratorInitialStore[classKey] = {};
  7106. }
  7107. return __decoratorInitialStore[classKey];
  7108. }
  7109. /**
  7110. * Return the list of properties flagged as serializable
  7111. * @param target: host object
  7112. */
  7113. function getMergedStore(target) {
  7114. var classKey = target.getClassName();
  7115. if (__mergedStore[classKey]) {
  7116. return __mergedStore[classKey];
  7117. }
  7118. __mergedStore[classKey] = {};
  7119. var store = __mergedStore[classKey];
  7120. var currentTarget = target;
  7121. var currentKey = classKey;
  7122. while (currentKey) {
  7123. var initialStore = __decoratorInitialStore[currentKey];
  7124. for (var property in initialStore) {
  7125. store[property] = initialStore[property];
  7126. }
  7127. var parent_1 = void 0;
  7128. var done = false;
  7129. do {
  7130. parent_1 = Object.getPrototypeOf(currentTarget);
  7131. if (!parent_1.getClassName) {
  7132. done = true;
  7133. break;
  7134. }
  7135. if (parent_1.getClassName() !== currentKey) {
  7136. break;
  7137. }
  7138. currentTarget = parent_1;
  7139. } while (parent_1);
  7140. if (done) {
  7141. break;
  7142. }
  7143. currentKey = parent_1.getClassName();
  7144. currentTarget = parent_1;
  7145. }
  7146. return store;
  7147. }
  7148. function generateSerializableMember(type, sourceName) {
  7149. return function (target, propertyKey) {
  7150. var classStore = getDirectStore(target);
  7151. if (!classStore[propertyKey]) {
  7152. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7153. }
  7154. };
  7155. }
  7156. function generateExpandMember(setCallback, targetKey) {
  7157. if (targetKey === void 0) { targetKey = null; }
  7158. return function (target, propertyKey) {
  7159. var key = targetKey || ("_" + propertyKey);
  7160. Object.defineProperty(target, propertyKey, {
  7161. get: function () {
  7162. return this[key];
  7163. },
  7164. set: function (value) {
  7165. if (this[key] === value) {
  7166. return;
  7167. }
  7168. this[key] = value;
  7169. target[setCallback].apply(this);
  7170. },
  7171. enumerable: true,
  7172. configurable: true
  7173. });
  7174. };
  7175. }
  7176. function expandToProperty(callback, targetKey) {
  7177. if (targetKey === void 0) { targetKey = null; }
  7178. return generateExpandMember(callback, targetKey);
  7179. }
  7180. BABYLON.expandToProperty = expandToProperty;
  7181. function serialize(sourceName) {
  7182. return generateSerializableMember(0, sourceName); // value member
  7183. }
  7184. BABYLON.serialize = serialize;
  7185. function serializeAsTexture(sourceName) {
  7186. return generateSerializableMember(1, sourceName); // texture member
  7187. }
  7188. BABYLON.serializeAsTexture = serializeAsTexture;
  7189. function serializeAsColor3(sourceName) {
  7190. return generateSerializableMember(2, sourceName); // color3 member
  7191. }
  7192. BABYLON.serializeAsColor3 = serializeAsColor3;
  7193. function serializeAsFresnelParameters(sourceName) {
  7194. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7195. }
  7196. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7197. function serializeAsVector2(sourceName) {
  7198. return generateSerializableMember(4, sourceName); // vector2 member
  7199. }
  7200. BABYLON.serializeAsVector2 = serializeAsVector2;
  7201. function serializeAsVector3(sourceName) {
  7202. return generateSerializableMember(5, sourceName); // vector3 member
  7203. }
  7204. BABYLON.serializeAsVector3 = serializeAsVector3;
  7205. function serializeAsMeshReference(sourceName) {
  7206. return generateSerializableMember(6, sourceName); // mesh reference member
  7207. }
  7208. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7209. function serializeAsColorCurves(sourceName) {
  7210. return generateSerializableMember(7, sourceName); // color curves
  7211. }
  7212. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7213. function serializeAsColor4(sourceName) {
  7214. return generateSerializableMember(8, sourceName); // color 4
  7215. }
  7216. BABYLON.serializeAsColor4 = serializeAsColor4;
  7217. function serializeAsImageProcessingConfiguration(sourceName) {
  7218. return generateSerializableMember(9, sourceName); // image processing
  7219. }
  7220. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7221. function serializeAsQuaternion(sourceName) {
  7222. return generateSerializableMember(10, sourceName); // quaternion member
  7223. }
  7224. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7225. var SerializationHelper = /** @class */ (function () {
  7226. function SerializationHelper() {
  7227. }
  7228. SerializationHelper.Serialize = function (entity, serializationObject) {
  7229. if (!serializationObject) {
  7230. serializationObject = {};
  7231. }
  7232. // Tags
  7233. if (BABYLON.Tags) {
  7234. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7235. }
  7236. var serializedProperties = getMergedStore(entity);
  7237. // Properties
  7238. for (var property in serializedProperties) {
  7239. var propertyDescriptor = serializedProperties[property];
  7240. var targetPropertyName = propertyDescriptor.sourceName || property;
  7241. var propertyType = propertyDescriptor.type;
  7242. var sourceProperty = entity[property];
  7243. if (sourceProperty !== undefined && sourceProperty !== null) {
  7244. switch (propertyType) {
  7245. case 0:// Value
  7246. serializationObject[targetPropertyName] = sourceProperty;
  7247. break;
  7248. case 1:// Texture
  7249. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7250. break;
  7251. case 2:// Color3
  7252. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7253. break;
  7254. case 3:// FresnelParameters
  7255. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7256. break;
  7257. case 4:// Vector2
  7258. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7259. break;
  7260. case 5:// Vector3
  7261. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7262. break;
  7263. case 6:// Mesh reference
  7264. serializationObject[targetPropertyName] = sourceProperty.id;
  7265. break;
  7266. case 7:// Color Curves
  7267. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7268. break;
  7269. case 8:// Color 4
  7270. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7271. break;
  7272. case 9:// Image Processing
  7273. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7274. break;
  7275. }
  7276. }
  7277. }
  7278. return serializationObject;
  7279. };
  7280. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7281. if (rootUrl === void 0) { rootUrl = null; }
  7282. var destination = creationFunction();
  7283. if (!rootUrl) {
  7284. rootUrl = "";
  7285. }
  7286. // Tags
  7287. if (BABYLON.Tags) {
  7288. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7289. }
  7290. var classStore = getMergedStore(destination);
  7291. // Properties
  7292. for (var property in classStore) {
  7293. var propertyDescriptor = classStore[property];
  7294. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7295. var propertyType = propertyDescriptor.type;
  7296. if (sourceProperty !== undefined && sourceProperty !== null) {
  7297. var dest = destination;
  7298. switch (propertyType) {
  7299. case 0:// Value
  7300. dest[property] = sourceProperty;
  7301. break;
  7302. case 1:// Texture
  7303. if (scene) {
  7304. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7305. }
  7306. break;
  7307. case 2:// Color3
  7308. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7309. break;
  7310. case 3:// FresnelParameters
  7311. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7312. break;
  7313. case 4:// Vector2
  7314. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7315. break;
  7316. case 5:// Vector3
  7317. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7318. break;
  7319. case 6:// Mesh reference
  7320. if (scene) {
  7321. dest[property] = scene.getLastMeshByID(sourceProperty);
  7322. }
  7323. break;
  7324. case 7:// Color Curves
  7325. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7326. break;
  7327. case 8:// Color 4
  7328. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7329. break;
  7330. case 9:// Image Processing
  7331. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7332. break;
  7333. }
  7334. }
  7335. }
  7336. return destination;
  7337. };
  7338. SerializationHelper.Clone = function (creationFunction, source) {
  7339. return _copySource(creationFunction, source, false);
  7340. };
  7341. SerializationHelper.Instanciate = function (creationFunction, source) {
  7342. return _copySource(creationFunction, source, true);
  7343. };
  7344. return SerializationHelper;
  7345. }());
  7346. BABYLON.SerializationHelper = SerializationHelper;
  7347. })(BABYLON || (BABYLON = {}));
  7348. //# sourceMappingURL=babylon.decorators.js.map
  7349. "use strict";
  7350. var BABYLON;
  7351. (function (BABYLON) {
  7352. /**
  7353. * Wrapper class for promise with external resolve and reject.
  7354. */
  7355. var Deferred = /** @class */ (function () {
  7356. /**
  7357. * Constructor for this deferred object.
  7358. */
  7359. function Deferred() {
  7360. var _this = this;
  7361. this.promise = new Promise(function (resolve, reject) {
  7362. _this._resolve = resolve;
  7363. _this._reject = reject;
  7364. });
  7365. }
  7366. Object.defineProperty(Deferred.prototype, "resolve", {
  7367. /**
  7368. * The resolve method of the promise associated with this deferred object.
  7369. */
  7370. get: function () {
  7371. return this._resolve;
  7372. },
  7373. enumerable: true,
  7374. configurable: true
  7375. });
  7376. Object.defineProperty(Deferred.prototype, "reject", {
  7377. /**
  7378. * The reject method of the promise associated with this deferred object.
  7379. */
  7380. get: function () {
  7381. return this._reject;
  7382. },
  7383. enumerable: true,
  7384. configurable: true
  7385. });
  7386. return Deferred;
  7387. }());
  7388. BABYLON.Deferred = Deferred;
  7389. })(BABYLON || (BABYLON = {}));
  7390. //# sourceMappingURL=babylon.deferred.js.map
  7391. "use strict";
  7392. var BABYLON;
  7393. (function (BABYLON) {
  7394. /**
  7395. * A class serves as a medium between the observable and its observers
  7396. */
  7397. var EventState = /** @class */ (function () {
  7398. /**
  7399. * Create a new EventState
  7400. * @param mask defines the mask associated with this state
  7401. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7402. * @param target defines the original target of the state
  7403. * @param currentTarget defines the current target of the state
  7404. */
  7405. function EventState(mask, skipNextObservers, target, currentTarget) {
  7406. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7407. this.initalize(mask, skipNextObservers, target, currentTarget);
  7408. }
  7409. /**
  7410. * Initialize the current event state
  7411. * @param mask defines the mask associated with this state
  7412. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7413. * @param target defines the original target of the state
  7414. * @param currentTarget defines the current target of the state
  7415. * @returns the current event state
  7416. */
  7417. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7418. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7419. this.mask = mask;
  7420. this.skipNextObservers = skipNextObservers;
  7421. this.target = target;
  7422. this.currentTarget = currentTarget;
  7423. return this;
  7424. };
  7425. return EventState;
  7426. }());
  7427. BABYLON.EventState = EventState;
  7428. /**
  7429. * Represent an Observer registered to a given Observable object.
  7430. */
  7431. var Observer = /** @class */ (function () {
  7432. /**
  7433. * Creates a new observer
  7434. * @param callback defines the callback to call when the observer is notified
  7435. * @param mask defines the mask of the observer (used to filter notifications)
  7436. * @param scope defines the current scope used to restore the JS context
  7437. */
  7438. function Observer(
  7439. /**
  7440. * Defines the callback to call when the observer is notified
  7441. */
  7442. callback,
  7443. /**
  7444. * Defines the mask of the observer (used to filter notifications)
  7445. */
  7446. mask,
  7447. /**
  7448. * Defines the current scope used to restore the JS context
  7449. */
  7450. scope) {
  7451. if (scope === void 0) { scope = null; }
  7452. this.callback = callback;
  7453. this.mask = mask;
  7454. this.scope = scope;
  7455. /** @ignore */
  7456. this._willBeUnregistered = false;
  7457. /**
  7458. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7459. */
  7460. this.unregisterOnNextCall = false;
  7461. }
  7462. return Observer;
  7463. }());
  7464. BABYLON.Observer = Observer;
  7465. /**
  7466. * Represent a list of observers registered to multiple Observables object.
  7467. */
  7468. var MultiObserver = /** @class */ (function () {
  7469. function MultiObserver() {
  7470. }
  7471. /**
  7472. * Release associated resources
  7473. */
  7474. MultiObserver.prototype.dispose = function () {
  7475. if (this._observers && this._observables) {
  7476. for (var index = 0; index < this._observers.length; index++) {
  7477. this._observables[index].remove(this._observers[index]);
  7478. }
  7479. }
  7480. this._observers = null;
  7481. this._observables = null;
  7482. };
  7483. /**
  7484. * Raise a callback when one of the observable will notify
  7485. * @param observables defines a list of observables to watch
  7486. * @param callback defines the callback to call on notification
  7487. * @param mask defines the mask used to filter notifications
  7488. * @param scope defines the current scope used to restore the JS context
  7489. * @returns the new MultiObserver
  7490. */
  7491. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7492. if (mask === void 0) { mask = -1; }
  7493. if (scope === void 0) { scope = null; }
  7494. var result = new MultiObserver();
  7495. result._observers = new Array();
  7496. result._observables = observables;
  7497. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7498. var observable = observables_1[_i];
  7499. var observer = observable.add(callback, mask, false, scope);
  7500. if (observer) {
  7501. result._observers.push(observer);
  7502. }
  7503. }
  7504. return result;
  7505. };
  7506. return MultiObserver;
  7507. }());
  7508. BABYLON.MultiObserver = MultiObserver;
  7509. /**
  7510. * The Observable class is a simple implementation of the Observable pattern.
  7511. * 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.
  7512. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7513. * 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).
  7514. * 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.
  7515. */
  7516. var Observable = /** @class */ (function () {
  7517. /**
  7518. * Creates a new observable
  7519. * @param onObserverAdded defines a callback to call when a new observer is added
  7520. */
  7521. function Observable(onObserverAdded) {
  7522. this._observers = new Array();
  7523. this._eventState = new EventState(0);
  7524. if (onObserverAdded) {
  7525. this._onObserverAdded = onObserverAdded;
  7526. }
  7527. }
  7528. /**
  7529. * Create a new Observer with the specified callback
  7530. * @param callback the callback that will be executed for that Observer
  7531. * @param mask the mask used to filter observers
  7532. * @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.
  7533. * @param scope optional scope for the callback to be called from
  7534. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7535. * @returns the new observer created for the callback
  7536. */
  7537. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7538. if (mask === void 0) { mask = -1; }
  7539. if (insertFirst === void 0) { insertFirst = false; }
  7540. if (scope === void 0) { scope = null; }
  7541. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7542. if (!callback) {
  7543. return null;
  7544. }
  7545. var observer = new Observer(callback, mask, scope);
  7546. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7547. if (insertFirst) {
  7548. this._observers.unshift(observer);
  7549. }
  7550. else {
  7551. this._observers.push(observer);
  7552. }
  7553. if (this._onObserverAdded) {
  7554. this._onObserverAdded(observer);
  7555. }
  7556. return observer;
  7557. };
  7558. /**
  7559. * Remove an Observer from the Observable object
  7560. * @param observer the instance of the Observer to remove
  7561. * @returns false if it doesn't belong to this Observable
  7562. */
  7563. Observable.prototype.remove = function (observer) {
  7564. if (!observer) {
  7565. return false;
  7566. }
  7567. var index = this._observers.indexOf(observer);
  7568. if (index !== -1) {
  7569. this._observers.splice(index, 1);
  7570. return true;
  7571. }
  7572. return false;
  7573. };
  7574. /**
  7575. * Remove a callback from the Observable object
  7576. * @param callback the callback to remove
  7577. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7578. * @returns false if it doesn't belong to this Observable
  7579. */
  7580. Observable.prototype.removeCallback = function (callback, scope) {
  7581. for (var index = 0; index < this._observers.length; index++) {
  7582. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7583. this._observers.splice(index, 1);
  7584. return true;
  7585. }
  7586. }
  7587. return false;
  7588. };
  7589. Observable.prototype._deferUnregister = function (observer) {
  7590. var _this = this;
  7591. observer.unregisterOnNextCall = false;
  7592. observer._willBeUnregistered = true;
  7593. BABYLON.Tools.SetImmediate(function () {
  7594. _this.remove(observer);
  7595. });
  7596. };
  7597. /**
  7598. * Notify all Observers by calling their respective callback with the given data
  7599. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7600. * @param eventData defines the data to send to all observers
  7601. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7602. * @param target defines the original target of the state
  7603. * @param currentTarget defines the current target of the state
  7604. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7605. */
  7606. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7607. if (mask === void 0) { mask = -1; }
  7608. if (!this._observers.length) {
  7609. return true;
  7610. }
  7611. var state = this._eventState;
  7612. state.mask = mask;
  7613. state.target = target;
  7614. state.currentTarget = currentTarget;
  7615. state.skipNextObservers = false;
  7616. state.lastReturnValue = eventData;
  7617. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7618. var obs = _a[_i];
  7619. if (obs._willBeUnregistered) {
  7620. continue;
  7621. }
  7622. if (obs.mask & mask) {
  7623. if (obs.scope) {
  7624. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7625. }
  7626. else {
  7627. state.lastReturnValue = obs.callback(eventData, state);
  7628. }
  7629. if (obs.unregisterOnNextCall) {
  7630. this._deferUnregister(obs);
  7631. }
  7632. }
  7633. if (state.skipNextObservers) {
  7634. return false;
  7635. }
  7636. }
  7637. return true;
  7638. };
  7639. /**
  7640. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7641. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7642. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7643. * and it is crucial that all callbacks will be executed.
  7644. * The order of the callbacks is kept, callbacks are not executed parallel.
  7645. *
  7646. * @param eventData The data to be sent to each callback
  7647. * @param mask is used to filter observers defaults to -1
  7648. * @param target defines the callback target (see EventState)
  7649. * @param currentTarget defines he current object in the bubbling phase
  7650. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7651. */
  7652. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7653. var _this = this;
  7654. if (mask === void 0) { mask = -1; }
  7655. // create an empty promise
  7656. var p = Promise.resolve(eventData);
  7657. // no observers? return this promise.
  7658. if (!this._observers.length) {
  7659. return p;
  7660. }
  7661. var state = this._eventState;
  7662. state.mask = mask;
  7663. state.target = target;
  7664. state.currentTarget = currentTarget;
  7665. state.skipNextObservers = false;
  7666. // execute one callback after another (not using Promise.all, the order is important)
  7667. this._observers.forEach(function (obs) {
  7668. if (state.skipNextObservers) {
  7669. return;
  7670. }
  7671. if (obs._willBeUnregistered) {
  7672. return;
  7673. }
  7674. if (obs.mask & mask) {
  7675. if (obs.scope) {
  7676. p = p.then(function (lastReturnedValue) {
  7677. state.lastReturnValue = lastReturnedValue;
  7678. return obs.callback.apply(obs.scope, [eventData, state]);
  7679. });
  7680. }
  7681. else {
  7682. p = p.then(function (lastReturnedValue) {
  7683. state.lastReturnValue = lastReturnedValue;
  7684. return obs.callback(eventData, state);
  7685. });
  7686. }
  7687. if (obs.unregisterOnNextCall) {
  7688. _this._deferUnregister(obs);
  7689. }
  7690. }
  7691. });
  7692. // return the eventData
  7693. return p.then(function () { return eventData; });
  7694. };
  7695. /**
  7696. * Notify a specific observer
  7697. * @param observer defines the observer to notify
  7698. * @param eventData defines the data to be sent to each callback
  7699. * @param mask is used to filter observers defaults to -1
  7700. */
  7701. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7702. if (mask === void 0) { mask = -1; }
  7703. var state = this._eventState;
  7704. state.mask = mask;
  7705. state.skipNextObservers = false;
  7706. observer.callback(eventData, state);
  7707. };
  7708. /**
  7709. * Gets a boolean indicating if the observable has at least one observer
  7710. * @returns true is the Observable has at least one Observer registered
  7711. */
  7712. Observable.prototype.hasObservers = function () {
  7713. return this._observers.length > 0;
  7714. };
  7715. /**
  7716. * Clear the list of observers
  7717. */
  7718. Observable.prototype.clear = function () {
  7719. this._observers = new Array();
  7720. this._onObserverAdded = null;
  7721. };
  7722. /**
  7723. * Clone the current observable
  7724. * @returns a new observable
  7725. */
  7726. Observable.prototype.clone = function () {
  7727. var result = new Observable();
  7728. result._observers = this._observers.slice(0);
  7729. return result;
  7730. };
  7731. /**
  7732. * Does this observable handles observer registered with a given mask
  7733. * @param mask defines the mask to be tested
  7734. * @return whether or not one observer registered with the given mask is handeled
  7735. **/
  7736. Observable.prototype.hasSpecificMask = function (mask) {
  7737. if (mask === void 0) { mask = -1; }
  7738. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7739. var obs = _a[_i];
  7740. if (obs.mask & mask || obs.mask === mask) {
  7741. return true;
  7742. }
  7743. }
  7744. return false;
  7745. };
  7746. return Observable;
  7747. }());
  7748. BABYLON.Observable = Observable;
  7749. })(BABYLON || (BABYLON = {}));
  7750. //# sourceMappingURL=babylon.observable.js.map
  7751. "use strict";
  7752. var BABYLON;
  7753. (function (BABYLON) {
  7754. var SmartArray = /** @class */ (function () {
  7755. function SmartArray(capacity) {
  7756. this.length = 0;
  7757. this.data = new Array(capacity);
  7758. this._id = SmartArray._GlobalId++;
  7759. }
  7760. SmartArray.prototype.push = function (value) {
  7761. this.data[this.length++] = value;
  7762. if (this.length > this.data.length) {
  7763. this.data.length *= 2;
  7764. }
  7765. };
  7766. SmartArray.prototype.forEach = function (func) {
  7767. for (var index = 0; index < this.length; index++) {
  7768. func(this.data[index]);
  7769. }
  7770. };
  7771. SmartArray.prototype.sort = function (compareFn) {
  7772. this.data.sort(compareFn);
  7773. };
  7774. SmartArray.prototype.reset = function () {
  7775. this.length = 0;
  7776. };
  7777. SmartArray.prototype.dispose = function () {
  7778. this.reset();
  7779. if (this.data) {
  7780. this.data.length = 0;
  7781. this.data = [];
  7782. }
  7783. };
  7784. SmartArray.prototype.concat = function (array) {
  7785. if (array.length === 0) {
  7786. return;
  7787. }
  7788. if (this.length + array.length > this.data.length) {
  7789. this.data.length = (this.length + array.length) * 2;
  7790. }
  7791. for (var index = 0; index < array.length; index++) {
  7792. this.data[this.length++] = (array.data || array)[index];
  7793. }
  7794. };
  7795. SmartArray.prototype.indexOf = function (value) {
  7796. var position = this.data.indexOf(value);
  7797. if (position >= this.length) {
  7798. return -1;
  7799. }
  7800. return position;
  7801. };
  7802. SmartArray.prototype.contains = function (value) {
  7803. return this.data.indexOf(value) !== -1;
  7804. };
  7805. // Statics
  7806. SmartArray._GlobalId = 0;
  7807. return SmartArray;
  7808. }());
  7809. BABYLON.SmartArray = SmartArray;
  7810. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7811. __extends(SmartArrayNoDuplicate, _super);
  7812. function SmartArrayNoDuplicate() {
  7813. var _this = _super !== null && _super.apply(this, arguments) || this;
  7814. _this._duplicateId = 0;
  7815. return _this;
  7816. }
  7817. SmartArrayNoDuplicate.prototype.push = function (value) {
  7818. _super.prototype.push.call(this, value);
  7819. if (!value.__smartArrayFlags) {
  7820. value.__smartArrayFlags = {};
  7821. }
  7822. value.__smartArrayFlags[this._id] = this._duplicateId;
  7823. };
  7824. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7825. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7826. return false;
  7827. }
  7828. this.push(value);
  7829. return true;
  7830. };
  7831. SmartArrayNoDuplicate.prototype.reset = function () {
  7832. _super.prototype.reset.call(this);
  7833. this._duplicateId++;
  7834. };
  7835. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7836. if (array.length === 0) {
  7837. return;
  7838. }
  7839. if (this.length + array.length > this.data.length) {
  7840. this.data.length = (this.length + array.length) * 2;
  7841. }
  7842. for (var index = 0; index < array.length; index++) {
  7843. var item = (array.data || array)[index];
  7844. this.pushNoDuplicate(item);
  7845. }
  7846. };
  7847. return SmartArrayNoDuplicate;
  7848. }(SmartArray));
  7849. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7850. })(BABYLON || (BABYLON = {}));
  7851. //# sourceMappingURL=babylon.smartArray.js.map
  7852. "use strict";
  7853. var BABYLON;
  7854. (function (BABYLON) {
  7855. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7856. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7857. var LoadFileError = /** @class */ (function (_super) {
  7858. __extends(LoadFileError, _super);
  7859. function LoadFileError(message, request) {
  7860. var _this = _super.call(this, message) || this;
  7861. _this.request = request;
  7862. _this.name = "LoadFileError";
  7863. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7864. return _this;
  7865. }
  7866. // Polyfill for Object.setPrototypeOf if necessary.
  7867. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7868. return LoadFileError;
  7869. }(Error));
  7870. BABYLON.LoadFileError = LoadFileError;
  7871. var RetryStrategy = /** @class */ (function () {
  7872. function RetryStrategy() {
  7873. }
  7874. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7875. if (maxRetries === void 0) { maxRetries = 3; }
  7876. if (baseInterval === void 0) { baseInterval = 500; }
  7877. return function (url, request, retryIndex) {
  7878. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7879. return -1;
  7880. }
  7881. return Math.pow(2, retryIndex) * baseInterval;
  7882. };
  7883. };
  7884. return RetryStrategy;
  7885. }());
  7886. BABYLON.RetryStrategy = RetryStrategy;
  7887. // Screenshots
  7888. var screenshotCanvas;
  7889. var cloneValue = function (source, destinationObject) {
  7890. if (!source)
  7891. return null;
  7892. if (source instanceof BABYLON.Mesh) {
  7893. return null;
  7894. }
  7895. if (source instanceof BABYLON.SubMesh) {
  7896. return source.clone(destinationObject);
  7897. }
  7898. else if (source.clone) {
  7899. return source.clone();
  7900. }
  7901. return null;
  7902. };
  7903. var Tools = /** @class */ (function () {
  7904. function Tools() {
  7905. }
  7906. /**
  7907. * Interpolates between a and b via alpha
  7908. * @param a The lower value (returned when alpha = 0)
  7909. * @param b The upper value (returned when alpha = 1)
  7910. * @param alpha The interpolation-factor
  7911. * @return The mixed value
  7912. */
  7913. Tools.Mix = function (a, b, alpha) {
  7914. return a * (1 - alpha) + b * alpha;
  7915. };
  7916. Tools.Instantiate = function (className) {
  7917. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7918. return Tools.RegisteredExternalClasses[className];
  7919. }
  7920. var arr = className.split(".");
  7921. var fn = (window || this);
  7922. for (var i = 0, len = arr.length; i < len; i++) {
  7923. fn = fn[arr[i]];
  7924. }
  7925. if (typeof fn !== "function") {
  7926. return null;
  7927. }
  7928. return fn;
  7929. };
  7930. /**
  7931. * Provides a slice function that will work even on IE
  7932. * @param data defines the array to slice
  7933. * @returns the new sliced array
  7934. */
  7935. Tools.Slice = function (data) {
  7936. if (data.slice) {
  7937. return data.slice();
  7938. }
  7939. return Array.prototype.slice.call(data);
  7940. };
  7941. Tools.SetImmediate = function (action) {
  7942. if (window.setImmediate) {
  7943. window.setImmediate(action);
  7944. }
  7945. else {
  7946. setTimeout(action, 1);
  7947. }
  7948. };
  7949. Tools.IsExponentOfTwo = function (value) {
  7950. var count = 1;
  7951. do {
  7952. count *= 2;
  7953. } while (count < value);
  7954. return count === value;
  7955. };
  7956. /**
  7957. * Find the next highest power of two.
  7958. * @param x Number to start search from.
  7959. * @return Next highest power of two.
  7960. */
  7961. Tools.CeilingPOT = function (x) {
  7962. x--;
  7963. x |= x >> 1;
  7964. x |= x >> 2;
  7965. x |= x >> 4;
  7966. x |= x >> 8;
  7967. x |= x >> 16;
  7968. x++;
  7969. return x;
  7970. };
  7971. /**
  7972. * Find the next lowest power of two.
  7973. * @param x Number to start search from.
  7974. * @return Next lowest power of two.
  7975. */
  7976. Tools.FloorPOT = function (x) {
  7977. x = x | (x >> 1);
  7978. x = x | (x >> 2);
  7979. x = x | (x >> 4);
  7980. x = x | (x >> 8);
  7981. x = x | (x >> 16);
  7982. return x - (x >> 1);
  7983. };
  7984. /**
  7985. * Find the nearest power of two.
  7986. * @param x Number to start search from.
  7987. * @return Next nearest power of two.
  7988. */
  7989. Tools.NearestPOT = function (x) {
  7990. var c = Tools.CeilingPOT(x);
  7991. var f = Tools.FloorPOT(x);
  7992. return (c - x) > (x - f) ? f : c;
  7993. };
  7994. Tools.GetExponentOfTwo = function (value, max, mode) {
  7995. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7996. var pot;
  7997. switch (mode) {
  7998. case BABYLON.Engine.SCALEMODE_FLOOR:
  7999. pot = Tools.FloorPOT(value);
  8000. break;
  8001. case BABYLON.Engine.SCALEMODE_NEAREST:
  8002. pot = Tools.NearestPOT(value);
  8003. break;
  8004. case BABYLON.Engine.SCALEMODE_CEILING:
  8005. default:
  8006. pot = Tools.CeilingPOT(value);
  8007. break;
  8008. }
  8009. return Math.min(pot, max);
  8010. };
  8011. Tools.GetFilename = function (path) {
  8012. var index = path.lastIndexOf("/");
  8013. if (index < 0)
  8014. return path;
  8015. return path.substring(index + 1);
  8016. };
  8017. /**
  8018. * Extracts the "folder" part of a path (everything before the filename).
  8019. * @param uri The URI to extract the info from
  8020. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8021. * @returns The "folder" part of the path
  8022. */
  8023. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8024. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8025. var index = uri.lastIndexOf("/");
  8026. if (index < 0) {
  8027. if (returnUnchangedIfNoSlash) {
  8028. return uri;
  8029. }
  8030. return "";
  8031. }
  8032. return uri.substring(0, index + 1);
  8033. };
  8034. Tools.GetDOMTextContent = function (element) {
  8035. var result = "";
  8036. var child = element.firstChild;
  8037. while (child) {
  8038. if (child.nodeType === 3) {
  8039. result += child.textContent;
  8040. }
  8041. child = child.nextSibling;
  8042. }
  8043. return result;
  8044. };
  8045. Tools.ToDegrees = function (angle) {
  8046. return angle * 180 / Math.PI;
  8047. };
  8048. Tools.ToRadians = function (angle) {
  8049. return angle * Math.PI / 180;
  8050. };
  8051. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8052. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8053. var output = "";
  8054. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8055. var i = 0;
  8056. var bytes = new Uint8Array(buffer);
  8057. while (i < bytes.length) {
  8058. chr1 = bytes[i++];
  8059. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8060. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8061. enc1 = chr1 >> 2;
  8062. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8063. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8064. enc4 = chr3 & 63;
  8065. if (isNaN(chr2)) {
  8066. enc3 = enc4 = 64;
  8067. }
  8068. else if (isNaN(chr3)) {
  8069. enc4 = 64;
  8070. }
  8071. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8072. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8073. }
  8074. return "data:image/png;base64," + output;
  8075. };
  8076. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8077. if (bias === void 0) { bias = null; }
  8078. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8079. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8080. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8081. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8082. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8083. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8084. }
  8085. if (bias) {
  8086. minimum.x -= minimum.x * bias.x + bias.y;
  8087. minimum.y -= minimum.y * bias.x + bias.y;
  8088. minimum.z -= minimum.z * bias.x + bias.y;
  8089. maximum.x += maximum.x * bias.x + bias.y;
  8090. maximum.y += maximum.y * bias.x + bias.y;
  8091. maximum.z += maximum.z * bias.x + bias.y;
  8092. }
  8093. return {
  8094. minimum: minimum,
  8095. maximum: maximum
  8096. };
  8097. };
  8098. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8099. if (bias === void 0) { bias = null; }
  8100. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8101. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8102. if (!stride) {
  8103. stride = 3;
  8104. }
  8105. for (var index = start; index < start + count; index++) {
  8106. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8107. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8108. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8109. }
  8110. if (bias) {
  8111. minimum.x -= minimum.x * bias.x + bias.y;
  8112. minimum.y -= minimum.y * bias.x + bias.y;
  8113. minimum.z -= minimum.z * bias.x + bias.y;
  8114. maximum.x += maximum.x * bias.x + bias.y;
  8115. maximum.y += maximum.y * bias.x + bias.y;
  8116. maximum.z += maximum.z * bias.x + bias.y;
  8117. }
  8118. return {
  8119. minimum: minimum,
  8120. maximum: maximum
  8121. };
  8122. };
  8123. Tools.Vector2ArrayFeeder = function (array) {
  8124. return function (index) {
  8125. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8126. var length = isFloatArray ? array.length / 2 : array.length;
  8127. if (index >= length) {
  8128. return null;
  8129. }
  8130. if (isFloatArray) {
  8131. var fa = array;
  8132. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8133. }
  8134. var a = array;
  8135. return a[index];
  8136. };
  8137. };
  8138. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8139. if (bias === void 0) { bias = null; }
  8140. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8141. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8142. var i = 0;
  8143. var cur = feeder(i++);
  8144. while (cur) {
  8145. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8146. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8147. cur = feeder(i++);
  8148. }
  8149. if (bias) {
  8150. minimum.x -= minimum.x * bias.x + bias.y;
  8151. minimum.y -= minimum.y * bias.x + bias.y;
  8152. maximum.x += maximum.x * bias.x + bias.y;
  8153. maximum.y += maximum.y * bias.x + bias.y;
  8154. }
  8155. return {
  8156. minimum: minimum,
  8157. maximum: maximum
  8158. };
  8159. };
  8160. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8161. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8162. return null;
  8163. return Array.isArray(obj) ? obj : [obj];
  8164. };
  8165. // Misc.
  8166. Tools.GetPointerPrefix = function () {
  8167. var eventPrefix = "pointer";
  8168. // Check if pointer events are supported
  8169. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8170. eventPrefix = "mouse";
  8171. }
  8172. return eventPrefix;
  8173. };
  8174. /**
  8175. * @param func - the function to be called
  8176. * @param requester - the object that will request the next frame. Falls back to window.
  8177. */
  8178. Tools.QueueNewFrame = function (func, requester) {
  8179. if (!Tools.IsWindowObjectExist()) {
  8180. return setTimeout(func, 16);
  8181. }
  8182. if (!requester) {
  8183. requester = window;
  8184. }
  8185. if (requester.requestAnimationFrame) {
  8186. return requester.requestAnimationFrame(func);
  8187. }
  8188. else if (requester.msRequestAnimationFrame) {
  8189. return requester.msRequestAnimationFrame(func);
  8190. }
  8191. else if (requester.webkitRequestAnimationFrame) {
  8192. return requester.webkitRequestAnimationFrame(func);
  8193. }
  8194. else if (requester.mozRequestAnimationFrame) {
  8195. return requester.mozRequestAnimationFrame(func);
  8196. }
  8197. else if (requester.oRequestAnimationFrame) {
  8198. return requester.oRequestAnimationFrame(func);
  8199. }
  8200. else {
  8201. return window.setTimeout(func, 16);
  8202. }
  8203. };
  8204. Tools.RequestFullscreen = function (element) {
  8205. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8206. if (!requestFunction)
  8207. return;
  8208. requestFunction.call(element);
  8209. };
  8210. Tools.ExitFullscreen = function () {
  8211. if (document.exitFullscreen) {
  8212. document.exitFullscreen();
  8213. }
  8214. else if (document.mozCancelFullScreen) {
  8215. document.mozCancelFullScreen();
  8216. }
  8217. else if (document.webkitCancelFullScreen) {
  8218. document.webkitCancelFullScreen();
  8219. }
  8220. else if (document.msCancelFullScreen) {
  8221. document.msCancelFullScreen();
  8222. }
  8223. };
  8224. Tools.SetCorsBehavior = function (url, element) {
  8225. if (url && url.indexOf("data:") === 0) {
  8226. return;
  8227. }
  8228. if (Tools.CorsBehavior) {
  8229. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8230. element.crossOrigin = Tools.CorsBehavior;
  8231. }
  8232. else {
  8233. var result = Tools.CorsBehavior(url);
  8234. if (result) {
  8235. element.crossOrigin = result;
  8236. }
  8237. }
  8238. }
  8239. };
  8240. // External files
  8241. Tools.CleanUrl = function (url) {
  8242. url = url.replace(/#/mg, "%23");
  8243. return url;
  8244. };
  8245. Tools.LoadImage = function (url, onLoad, onError, database) {
  8246. if (url instanceof ArrayBuffer) {
  8247. url = Tools.EncodeArrayBufferTobase64(url);
  8248. }
  8249. url = Tools.CleanUrl(url);
  8250. url = Tools.PreprocessUrl(url);
  8251. var img = new Image();
  8252. Tools.SetCorsBehavior(url, img);
  8253. var loadHandler = function () {
  8254. img.removeEventListener("load", loadHandler);
  8255. img.removeEventListener("error", errorHandler);
  8256. onLoad(img);
  8257. };
  8258. var errorHandler = function (err) {
  8259. img.removeEventListener("load", loadHandler);
  8260. img.removeEventListener("error", errorHandler);
  8261. Tools.Error("Error while trying to load image: " + url);
  8262. if (onError) {
  8263. onError("Error while trying to load image: " + url, err);
  8264. }
  8265. };
  8266. img.addEventListener("load", loadHandler);
  8267. img.addEventListener("error", errorHandler);
  8268. var noIndexedDB = function () {
  8269. img.src = url;
  8270. };
  8271. var loadFromIndexedDB = function () {
  8272. if (database) {
  8273. database.loadImageFromDB(url, img);
  8274. }
  8275. };
  8276. //ANY database to do!
  8277. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8278. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8279. }
  8280. else {
  8281. if (url.indexOf("file:") !== -1) {
  8282. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8283. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8284. try {
  8285. var blobURL;
  8286. try {
  8287. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8288. }
  8289. catch (ex) {
  8290. // Chrome doesn't support oneTimeOnly parameter
  8291. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8292. }
  8293. img.src = blobURL;
  8294. }
  8295. catch (e) {
  8296. img.src = "";
  8297. }
  8298. return img;
  8299. }
  8300. }
  8301. noIndexedDB();
  8302. }
  8303. return img;
  8304. };
  8305. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8306. url = Tools.CleanUrl(url);
  8307. url = Tools.PreprocessUrl(url);
  8308. // If file and file input are set
  8309. if (url.indexOf("file:") !== -1) {
  8310. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8311. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8312. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8313. }
  8314. }
  8315. var loadUrl = Tools.BaseUrl + url;
  8316. var aborted = false;
  8317. var fileRequest = {
  8318. onCompleteObservable: new BABYLON.Observable(),
  8319. abort: function () { return aborted = true; },
  8320. };
  8321. var requestFile = function () {
  8322. var request = new XMLHttpRequest();
  8323. var retryHandle = null;
  8324. fileRequest.abort = function () {
  8325. aborted = true;
  8326. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8327. request.abort();
  8328. }
  8329. if (retryHandle !== null) {
  8330. clearTimeout(retryHandle);
  8331. retryHandle = null;
  8332. }
  8333. };
  8334. var retryLoop = function (retryIndex) {
  8335. request.open('GET', loadUrl, true);
  8336. if (useArrayBuffer) {
  8337. request.responseType = "arraybuffer";
  8338. }
  8339. if (onProgress) {
  8340. request.addEventListener("progress", onProgress);
  8341. }
  8342. var onLoadEnd = function () {
  8343. request.removeEventListener("loadend", onLoadEnd);
  8344. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8345. fileRequest.onCompleteObservable.clear();
  8346. };
  8347. request.addEventListener("loadend", onLoadEnd);
  8348. var onReadyStateChange = function () {
  8349. if (aborted) {
  8350. return;
  8351. }
  8352. // In case of undefined state in some browsers.
  8353. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8354. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8355. request.removeEventListener("readystatechange", onReadyStateChange);
  8356. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8357. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8358. return;
  8359. }
  8360. var retryStrategy = Tools.DefaultRetryStrategy;
  8361. if (retryStrategy) {
  8362. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8363. if (waitTime !== -1) {
  8364. // Prevent the request from completing for retry.
  8365. request.removeEventListener("loadend", onLoadEnd);
  8366. request = new XMLHttpRequest();
  8367. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8368. return;
  8369. }
  8370. }
  8371. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8372. if (onError) {
  8373. onError(request, e);
  8374. }
  8375. else {
  8376. throw e;
  8377. }
  8378. }
  8379. };
  8380. request.addEventListener("readystatechange", onReadyStateChange);
  8381. request.send();
  8382. };
  8383. retryLoop(0);
  8384. };
  8385. // Caching all files
  8386. if (database && database.enableSceneOffline) {
  8387. var noIndexedDB_1 = function () {
  8388. if (!aborted) {
  8389. requestFile();
  8390. }
  8391. };
  8392. var loadFromIndexedDB = function () {
  8393. // TODO: database needs to support aborting and should return a IFileRequest
  8394. if (aborted) {
  8395. return;
  8396. }
  8397. if (database) {
  8398. database.loadFileFromDB(url, function (data) {
  8399. if (!aborted) {
  8400. onSuccess(data);
  8401. }
  8402. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8403. }, onProgress ? function (event) {
  8404. if (!aborted) {
  8405. onProgress(event);
  8406. }
  8407. } : undefined, noIndexedDB_1, useArrayBuffer);
  8408. }
  8409. };
  8410. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8411. }
  8412. else {
  8413. requestFile();
  8414. }
  8415. return fileRequest;
  8416. };
  8417. /**
  8418. * Load a script (identified by an url). When the url returns, the
  8419. * content of this file is added into a new script element, attached to the DOM (body element)
  8420. */
  8421. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8422. var head = document.getElementsByTagName('head')[0];
  8423. var script = document.createElement('script');
  8424. script.type = 'text/javascript';
  8425. script.src = scriptUrl;
  8426. script.onload = function () {
  8427. if (onSuccess) {
  8428. onSuccess();
  8429. }
  8430. };
  8431. script.onerror = function (e) {
  8432. if (onError) {
  8433. onError("Unable to load script", e);
  8434. }
  8435. };
  8436. head.appendChild(script);
  8437. };
  8438. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8439. var reader = new FileReader();
  8440. var request = {
  8441. onCompleteObservable: new BABYLON.Observable(),
  8442. abort: function () { return reader.abort(); },
  8443. };
  8444. reader.onloadend = function (e) {
  8445. request.onCompleteObservable.notifyObservers(request);
  8446. };
  8447. reader.onload = function (e) {
  8448. //target doesn't have result from ts 1.3
  8449. callback(e.target['result']);
  8450. };
  8451. reader.onprogress = progressCallback;
  8452. reader.readAsDataURL(fileToLoad);
  8453. return request;
  8454. };
  8455. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8456. var reader = new FileReader();
  8457. var request = {
  8458. onCompleteObservable: new BABYLON.Observable(),
  8459. abort: function () { return reader.abort(); },
  8460. };
  8461. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8462. reader.onerror = function (e) {
  8463. Tools.Log("Error while reading file: " + fileToLoad.name);
  8464. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8465. };
  8466. reader.onload = function (e) {
  8467. //target doesn't have result from ts 1.3
  8468. callback(e.target['result']);
  8469. };
  8470. if (progressCallBack) {
  8471. reader.onprogress = progressCallBack;
  8472. }
  8473. if (!useArrayBuffer) {
  8474. // Asynchronous read
  8475. reader.readAsText(fileToLoad);
  8476. }
  8477. else {
  8478. reader.readAsArrayBuffer(fileToLoad);
  8479. }
  8480. return request;
  8481. };
  8482. //returns a downloadable url to a file content.
  8483. Tools.FileAsURL = function (content) {
  8484. var fileBlob = new Blob([content]);
  8485. var url = window.URL || window.webkitURL;
  8486. var link = url.createObjectURL(fileBlob);
  8487. return link;
  8488. };
  8489. // Misc.
  8490. Tools.Format = function (value, decimals) {
  8491. if (decimals === void 0) { decimals = 2; }
  8492. return value.toFixed(decimals);
  8493. };
  8494. Tools.CheckExtends = function (v, min, max) {
  8495. if (v.x < min.x)
  8496. min.x = v.x;
  8497. if (v.y < min.y)
  8498. min.y = v.y;
  8499. if (v.z < min.z)
  8500. min.z = v.z;
  8501. if (v.x > max.x)
  8502. max.x = v.x;
  8503. if (v.y > max.y)
  8504. max.y = v.y;
  8505. if (v.z > max.z)
  8506. max.z = v.z;
  8507. };
  8508. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8509. for (var prop in source) {
  8510. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8511. continue;
  8512. }
  8513. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8514. continue;
  8515. }
  8516. var sourceValue = source[prop];
  8517. var typeOfSourceValue = typeof sourceValue;
  8518. if (typeOfSourceValue === "function") {
  8519. continue;
  8520. }
  8521. try {
  8522. if (typeOfSourceValue === "object") {
  8523. if (sourceValue instanceof Array) {
  8524. destination[prop] = [];
  8525. if (sourceValue.length > 0) {
  8526. if (typeof sourceValue[0] == "object") {
  8527. for (var index = 0; index < sourceValue.length; index++) {
  8528. var clonedValue = cloneValue(sourceValue[index], destination);
  8529. if (destination[prop].indexOf(clonedValue) === -1) {
  8530. destination[prop].push(clonedValue);
  8531. }
  8532. }
  8533. }
  8534. else {
  8535. destination[prop] = sourceValue.slice(0);
  8536. }
  8537. }
  8538. }
  8539. else {
  8540. destination[prop] = cloneValue(sourceValue, destination);
  8541. }
  8542. }
  8543. else {
  8544. destination[prop] = sourceValue;
  8545. }
  8546. }
  8547. catch (e) {
  8548. // Just ignore error (it could be because of a read-only property)
  8549. }
  8550. }
  8551. };
  8552. Tools.IsEmpty = function (obj) {
  8553. for (var i in obj) {
  8554. if (obj.hasOwnProperty(i)) {
  8555. return false;
  8556. }
  8557. }
  8558. return true;
  8559. };
  8560. Tools.RegisterTopRootEvents = function (events) {
  8561. for (var index = 0; index < events.length; index++) {
  8562. var event = events[index];
  8563. window.addEventListener(event.name, event.handler, false);
  8564. try {
  8565. if (window.parent) {
  8566. window.parent.addEventListener(event.name, event.handler, false);
  8567. }
  8568. }
  8569. catch (e) {
  8570. // Silently fails...
  8571. }
  8572. }
  8573. };
  8574. Tools.UnregisterTopRootEvents = function (events) {
  8575. for (var index = 0; index < events.length; index++) {
  8576. var event = events[index];
  8577. window.removeEventListener(event.name, event.handler);
  8578. try {
  8579. if (window.parent) {
  8580. window.parent.removeEventListener(event.name, event.handler);
  8581. }
  8582. }
  8583. catch (e) {
  8584. // Silently fails...
  8585. }
  8586. }
  8587. };
  8588. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8589. if (mimeType === void 0) { mimeType = "image/png"; }
  8590. // Read the contents of the framebuffer
  8591. var numberOfChannelsByLine = width * 4;
  8592. var halfHeight = height / 2;
  8593. //Reading datas from WebGL
  8594. var data = engine.readPixels(0, 0, width, height);
  8595. //To flip image on Y axis.
  8596. for (var i = 0; i < halfHeight; i++) {
  8597. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8598. var currentCell = j + i * numberOfChannelsByLine;
  8599. var targetLine = height - i - 1;
  8600. var targetCell = j + targetLine * numberOfChannelsByLine;
  8601. var temp = data[currentCell];
  8602. data[currentCell] = data[targetCell];
  8603. data[targetCell] = temp;
  8604. }
  8605. }
  8606. // Create a 2D canvas to store the result
  8607. if (!screenshotCanvas) {
  8608. screenshotCanvas = document.createElement('canvas');
  8609. }
  8610. screenshotCanvas.width = width;
  8611. screenshotCanvas.height = height;
  8612. var context = screenshotCanvas.getContext('2d');
  8613. if (context) {
  8614. // Copy the pixels to a 2D canvas
  8615. var imageData = context.createImageData(width, height);
  8616. var castData = (imageData.data);
  8617. castData.set(data);
  8618. context.putImageData(imageData, 0, 0);
  8619. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8620. }
  8621. };
  8622. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8623. if (mimeType === void 0) { mimeType = "image/png"; }
  8624. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8625. if (successCallback) {
  8626. successCallback(base64Image);
  8627. }
  8628. else {
  8629. // We need HTMLCanvasElement.toBlob for HD screenshots
  8630. if (!screenshotCanvas.toBlob) {
  8631. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8632. screenshotCanvas.toBlob = function (callback, type, quality) {
  8633. var _this = this;
  8634. setTimeout(function () {
  8635. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8636. for (var i = 0; i < len; i++) {
  8637. arr[i] = binStr.charCodeAt(i);
  8638. }
  8639. callback(new Blob([arr], { type: type || 'image/png' }));
  8640. });
  8641. };
  8642. }
  8643. screenshotCanvas.toBlob(function (blob) {
  8644. var url = URL.createObjectURL(blob);
  8645. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8646. if (("download" in document.createElement("a"))) {
  8647. var a = window.document.createElement("a");
  8648. a.href = url;
  8649. if (fileName) {
  8650. a.setAttribute("download", fileName);
  8651. }
  8652. else {
  8653. var date = new Date();
  8654. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8655. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8656. }
  8657. window.document.body.appendChild(a);
  8658. a.addEventListener("click", function () {
  8659. if (a.parentElement) {
  8660. a.parentElement.removeChild(a);
  8661. }
  8662. });
  8663. a.click();
  8664. }
  8665. else {
  8666. var newWindow = window.open("");
  8667. if (!newWindow)
  8668. return;
  8669. var img = newWindow.document.createElement("img");
  8670. img.onload = function () {
  8671. // no longer need to read the blob so it's revoked
  8672. URL.revokeObjectURL(url);
  8673. };
  8674. img.src = url;
  8675. newWindow.document.body.appendChild(img);
  8676. }
  8677. });
  8678. }
  8679. };
  8680. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8681. if (mimeType === void 0) { mimeType = "image/png"; }
  8682. var width;
  8683. var height;
  8684. // If a precision value is specified
  8685. if (size.precision) {
  8686. width = Math.round(engine.getRenderWidth() * size.precision);
  8687. height = Math.round(width / engine.getAspectRatio(camera));
  8688. }
  8689. else if (size.width && size.height) {
  8690. width = size.width;
  8691. height = size.height;
  8692. }
  8693. else if (size.width && !size.height) {
  8694. width = size.width;
  8695. height = Math.round(width / engine.getAspectRatio(camera));
  8696. }
  8697. else if (size.height && !size.width) {
  8698. height = size.height;
  8699. width = Math.round(height * engine.getAspectRatio(camera));
  8700. }
  8701. else if (!isNaN(size)) {
  8702. height = size;
  8703. width = size;
  8704. }
  8705. else {
  8706. Tools.Error("Invalid 'size' parameter !");
  8707. return;
  8708. }
  8709. if (!screenshotCanvas) {
  8710. screenshotCanvas = document.createElement('canvas');
  8711. }
  8712. screenshotCanvas.width = width;
  8713. screenshotCanvas.height = height;
  8714. var renderContext = screenshotCanvas.getContext("2d");
  8715. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8716. var newWidth = width;
  8717. var newHeight = newWidth / ratio;
  8718. if (newHeight > height) {
  8719. newHeight = height;
  8720. newWidth = newHeight * ratio;
  8721. }
  8722. var offsetX = Math.max(0, width - newWidth) / 2;
  8723. var offsetY = Math.max(0, height - newHeight) / 2;
  8724. var renderingCanvas = engine.getRenderingCanvas();
  8725. if (renderContext && renderingCanvas) {
  8726. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8727. }
  8728. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8729. };
  8730. /**
  8731. * Generates an image screenshot from the specified camera.
  8732. *
  8733. * @param engine The engine to use for rendering
  8734. * @param camera The camera to use for rendering
  8735. * @param size This parameter can be set to a single number or to an object with the
  8736. * following (optional) properties: precision, width, height. If a single number is passed,
  8737. * it will be used for both width and height. If an object is passed, the screenshot size
  8738. * will be derived from the parameters. The precision property is a multiplier allowing
  8739. * rendering at a higher or lower resolution.
  8740. * @param successCallback The callback receives a single parameter which contains the
  8741. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8742. * src parameter of an <img> to display it.
  8743. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8744. * Check your browser for supported MIME types.
  8745. * @param samples Texture samples (default: 1)
  8746. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8747. * @param fileName A name for for the downloaded file.
  8748. * @constructor
  8749. */
  8750. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8751. if (mimeType === void 0) { mimeType = "image/png"; }
  8752. if (samples === void 0) { samples = 1; }
  8753. if (antialiasing === void 0) { antialiasing = false; }
  8754. var width;
  8755. var height;
  8756. //If a precision value is specified
  8757. if (size.precision) {
  8758. width = Math.round(engine.getRenderWidth() * size.precision);
  8759. height = Math.round(width / engine.getAspectRatio(camera));
  8760. size = { width: width, height: height };
  8761. }
  8762. else if (size.width && size.height) {
  8763. width = size.width;
  8764. height = size.height;
  8765. }
  8766. else if (size.width && !size.height) {
  8767. width = size.width;
  8768. height = Math.round(width / engine.getAspectRatio(camera));
  8769. size = { width: width, height: height };
  8770. }
  8771. else if (size.height && !size.width) {
  8772. height = size.height;
  8773. width = Math.round(height * engine.getAspectRatio(camera));
  8774. size = { width: width, height: height };
  8775. }
  8776. else if (!isNaN(size)) {
  8777. height = size;
  8778. width = size;
  8779. }
  8780. else {
  8781. Tools.Error("Invalid 'size' parameter !");
  8782. return;
  8783. }
  8784. var scene = camera.getScene();
  8785. var previousCamera = null;
  8786. if (scene.activeCamera !== camera) {
  8787. previousCamera = scene.activeCamera;
  8788. scene.activeCamera = camera;
  8789. }
  8790. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8791. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8792. texture.renderList = null;
  8793. texture.samples = samples;
  8794. if (antialiasing) {
  8795. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8796. }
  8797. texture.onAfterRenderObservable.add(function () {
  8798. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8799. });
  8800. scene.incrementRenderId();
  8801. scene.resetCachedMaterial();
  8802. texture.render(true);
  8803. texture.dispose();
  8804. if (previousCamera) {
  8805. scene.activeCamera = previousCamera;
  8806. }
  8807. camera.getProjectionMatrix(true); // Force cache refresh;
  8808. };
  8809. // XHR response validator for local file scenario
  8810. Tools.ValidateXHRData = function (xhr, dataType) {
  8811. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8812. if (dataType === void 0) { dataType = 7; }
  8813. try {
  8814. if (dataType & 1) {
  8815. if (xhr.responseText && xhr.responseText.length > 0) {
  8816. return true;
  8817. }
  8818. else if (dataType === 1) {
  8819. return false;
  8820. }
  8821. }
  8822. if (dataType & 2) {
  8823. // Check header width and height since there is no "TGA" magic number
  8824. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8825. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8826. return true;
  8827. }
  8828. else if (dataType === 2) {
  8829. return false;
  8830. }
  8831. }
  8832. if (dataType & 4) {
  8833. // Check for the "DDS" magic number
  8834. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8835. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8836. return true;
  8837. }
  8838. else {
  8839. return false;
  8840. }
  8841. }
  8842. }
  8843. catch (e) {
  8844. // Global protection
  8845. }
  8846. return false;
  8847. };
  8848. /**
  8849. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8850. * Be aware Math.random() could cause collisions, but:
  8851. * "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"
  8852. */
  8853. Tools.RandomId = function () {
  8854. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8855. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8856. return v.toString(16);
  8857. });
  8858. };
  8859. /**
  8860. * Test if the given uri is a base64 string.
  8861. * @param uri The uri to test
  8862. * @return True if the uri is a base64 string or false otherwise.
  8863. */
  8864. Tools.IsBase64 = function (uri) {
  8865. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8866. };
  8867. /**
  8868. * Decode the given base64 uri.
  8869. * @param uri The uri to decode
  8870. * @return The decoded base64 data.
  8871. */
  8872. Tools.DecodeBase64 = function (uri) {
  8873. var decodedString = atob(uri.split(",")[1]);
  8874. var bufferLength = decodedString.length;
  8875. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8876. for (var i = 0; i < bufferLength; i++) {
  8877. bufferView[i] = decodedString.charCodeAt(i);
  8878. }
  8879. return bufferView.buffer;
  8880. };
  8881. Object.defineProperty(Tools, "NoneLogLevel", {
  8882. get: function () {
  8883. return Tools._NoneLogLevel;
  8884. },
  8885. enumerable: true,
  8886. configurable: true
  8887. });
  8888. Object.defineProperty(Tools, "MessageLogLevel", {
  8889. get: function () {
  8890. return Tools._MessageLogLevel;
  8891. },
  8892. enumerable: true,
  8893. configurable: true
  8894. });
  8895. Object.defineProperty(Tools, "WarningLogLevel", {
  8896. get: function () {
  8897. return Tools._WarningLogLevel;
  8898. },
  8899. enumerable: true,
  8900. configurable: true
  8901. });
  8902. Object.defineProperty(Tools, "ErrorLogLevel", {
  8903. get: function () {
  8904. return Tools._ErrorLogLevel;
  8905. },
  8906. enumerable: true,
  8907. configurable: true
  8908. });
  8909. Object.defineProperty(Tools, "AllLogLevel", {
  8910. get: function () {
  8911. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8912. },
  8913. enumerable: true,
  8914. configurable: true
  8915. });
  8916. Tools._AddLogEntry = function (entry) {
  8917. Tools._LogCache = entry + Tools._LogCache;
  8918. if (Tools.OnNewCacheEntry) {
  8919. Tools.OnNewCacheEntry(entry);
  8920. }
  8921. };
  8922. Tools._FormatMessage = function (message) {
  8923. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8924. var date = new Date();
  8925. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8926. };
  8927. Tools._LogDisabled = function (message) {
  8928. // nothing to do
  8929. };
  8930. Tools._LogEnabled = function (message) {
  8931. var formattedMessage = Tools._FormatMessage(message);
  8932. console.log("BJS - " + formattedMessage);
  8933. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8934. Tools._AddLogEntry(entry);
  8935. };
  8936. Tools._WarnDisabled = function (message) {
  8937. // nothing to do
  8938. };
  8939. Tools._WarnEnabled = function (message) {
  8940. var formattedMessage = Tools._FormatMessage(message);
  8941. console.warn("BJS - " + formattedMessage);
  8942. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8943. Tools._AddLogEntry(entry);
  8944. };
  8945. Tools._ErrorDisabled = function (message) {
  8946. // nothing to do
  8947. };
  8948. Tools._ErrorEnabled = function (message) {
  8949. Tools.errorsCount++;
  8950. var formattedMessage = Tools._FormatMessage(message);
  8951. console.error("BJS - " + formattedMessage);
  8952. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8953. Tools._AddLogEntry(entry);
  8954. };
  8955. Object.defineProperty(Tools, "LogCache", {
  8956. get: function () {
  8957. return Tools._LogCache;
  8958. },
  8959. enumerable: true,
  8960. configurable: true
  8961. });
  8962. Tools.ClearLogCache = function () {
  8963. Tools._LogCache = "";
  8964. Tools.errorsCount = 0;
  8965. };
  8966. Object.defineProperty(Tools, "LogLevels", {
  8967. set: function (level) {
  8968. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8969. Tools.Log = Tools._LogEnabled;
  8970. }
  8971. else {
  8972. Tools.Log = Tools._LogDisabled;
  8973. }
  8974. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8975. Tools.Warn = Tools._WarnEnabled;
  8976. }
  8977. else {
  8978. Tools.Warn = Tools._WarnDisabled;
  8979. }
  8980. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8981. Tools.Error = Tools._ErrorEnabled;
  8982. }
  8983. else {
  8984. Tools.Error = Tools._ErrorDisabled;
  8985. }
  8986. },
  8987. enumerable: true,
  8988. configurable: true
  8989. });
  8990. Tools.IsWindowObjectExist = function () {
  8991. return (typeof window) !== "undefined";
  8992. };
  8993. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8994. get: function () {
  8995. return Tools._PerformanceNoneLogLevel;
  8996. },
  8997. enumerable: true,
  8998. configurable: true
  8999. });
  9000. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9001. get: function () {
  9002. return Tools._PerformanceUserMarkLogLevel;
  9003. },
  9004. enumerable: true,
  9005. configurable: true
  9006. });
  9007. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9008. get: function () {
  9009. return Tools._PerformanceConsoleLogLevel;
  9010. },
  9011. enumerable: true,
  9012. configurable: true
  9013. });
  9014. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9015. set: function (level) {
  9016. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9017. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9018. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9019. return;
  9020. }
  9021. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9022. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9023. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9024. return;
  9025. }
  9026. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9027. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9028. },
  9029. enumerable: true,
  9030. configurable: true
  9031. });
  9032. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9033. };
  9034. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9035. };
  9036. Tools._StartUserMark = function (counterName, condition) {
  9037. if (condition === void 0) { condition = true; }
  9038. if (!Tools._performance) {
  9039. if (!Tools.IsWindowObjectExist()) {
  9040. return;
  9041. }
  9042. Tools._performance = window.performance;
  9043. }
  9044. if (!condition || !Tools._performance.mark) {
  9045. return;
  9046. }
  9047. Tools._performance.mark(counterName + "-Begin");
  9048. };
  9049. Tools._EndUserMark = function (counterName, condition) {
  9050. if (condition === void 0) { condition = true; }
  9051. if (!condition || !Tools._performance.mark) {
  9052. return;
  9053. }
  9054. Tools._performance.mark(counterName + "-End");
  9055. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9056. };
  9057. Tools._StartPerformanceConsole = function (counterName, condition) {
  9058. if (condition === void 0) { condition = true; }
  9059. if (!condition) {
  9060. return;
  9061. }
  9062. Tools._StartUserMark(counterName, condition);
  9063. if (console.time) {
  9064. console.time(counterName);
  9065. }
  9066. };
  9067. Tools._EndPerformanceConsole = function (counterName, condition) {
  9068. if (condition === void 0) { condition = true; }
  9069. if (!condition) {
  9070. return;
  9071. }
  9072. Tools._EndUserMark(counterName, condition);
  9073. if (console.time) {
  9074. console.timeEnd(counterName);
  9075. }
  9076. };
  9077. Object.defineProperty(Tools, "Now", {
  9078. get: function () {
  9079. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9080. return window.performance.now();
  9081. }
  9082. return new Date().getTime();
  9083. },
  9084. enumerable: true,
  9085. configurable: true
  9086. });
  9087. /**
  9088. * This method will return the name of the class used to create the instance of the given object.
  9089. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9090. * @param object the object to get the class name from
  9091. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9092. */
  9093. Tools.GetClassName = function (object, isType) {
  9094. if (isType === void 0) { isType = false; }
  9095. var name = null;
  9096. if (!isType && object.getClassName) {
  9097. name = object.getClassName();
  9098. }
  9099. else {
  9100. if (object instanceof Object) {
  9101. var classObj = isType ? object : Object.getPrototypeOf(object);
  9102. name = classObj.constructor["__bjsclassName__"];
  9103. }
  9104. if (!name) {
  9105. name = typeof object;
  9106. }
  9107. }
  9108. return name;
  9109. };
  9110. Tools.First = function (array, predicate) {
  9111. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9112. var el = array_1[_i];
  9113. if (predicate(el)) {
  9114. return el;
  9115. }
  9116. }
  9117. return null;
  9118. };
  9119. /**
  9120. * This method will return the name of the full name of the class, including its owning module (if any).
  9121. * 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).
  9122. * @param object the object to get the class name from
  9123. * @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.
  9124. */
  9125. Tools.getFullClassName = function (object, isType) {
  9126. if (isType === void 0) { isType = false; }
  9127. var className = null;
  9128. var moduleName = null;
  9129. if (!isType && object.getClassName) {
  9130. className = object.getClassName();
  9131. }
  9132. else {
  9133. if (object instanceof Object) {
  9134. var classObj = isType ? object : Object.getPrototypeOf(object);
  9135. className = classObj.constructor["__bjsclassName__"];
  9136. moduleName = classObj.constructor["__bjsmoduleName__"];
  9137. }
  9138. if (!className) {
  9139. className = typeof object;
  9140. }
  9141. }
  9142. if (!className) {
  9143. return null;
  9144. }
  9145. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9146. };
  9147. /**
  9148. * 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.
  9149. * @param array
  9150. */
  9151. Tools.arrayOrStringFeeder = function (array) {
  9152. return function (index) {
  9153. if (index >= array.length) {
  9154. return null;
  9155. }
  9156. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9157. if (val && val.getHashCode) {
  9158. val = val.getHashCode();
  9159. }
  9160. if (typeof val === "string") {
  9161. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9162. }
  9163. return val;
  9164. };
  9165. };
  9166. /**
  9167. * Compute the hashCode of a stream of number
  9168. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9169. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9170. * @return the hash code computed
  9171. */
  9172. Tools.hashCodeFromStream = function (feeder) {
  9173. // Based from here: http://stackoverflow.com/a/7616484/802124
  9174. var hash = 0;
  9175. var index = 0;
  9176. var chr = feeder(index++);
  9177. while (chr != null) {
  9178. hash = ((hash << 5) - hash) + chr;
  9179. hash |= 0; // Convert to 32bit integer
  9180. chr = feeder(index++);
  9181. }
  9182. return hash;
  9183. };
  9184. /**
  9185. * Returns a promise that resolves after the given amount of time.
  9186. * @param delay Number of milliseconds to delay
  9187. * @returns Promise that resolves after the given amount of time
  9188. */
  9189. Tools.DelayAsync = function (delay) {
  9190. return new Promise(function (resolve) {
  9191. setTimeout(function () {
  9192. resolve();
  9193. }, delay);
  9194. });
  9195. };
  9196. Tools.BaseUrl = "";
  9197. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9198. /**
  9199. * Default behaviour for cors in the application.
  9200. * It can be a string if the expected behavior is identical in the entire app.
  9201. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9202. */
  9203. Tools.CorsBehavior = "anonymous";
  9204. Tools.UseFallbackTexture = true;
  9205. /**
  9206. * Use this object to register external classes like custom textures or material
  9207. * to allow the laoders to instantiate them
  9208. */
  9209. Tools.RegisteredExternalClasses = {};
  9210. // Used in case of a texture loading problem
  9211. 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";
  9212. Tools.PreprocessUrl = function (url) {
  9213. return url;
  9214. };
  9215. // Logs
  9216. Tools._NoneLogLevel = 0;
  9217. Tools._MessageLogLevel = 1;
  9218. Tools._WarningLogLevel = 2;
  9219. Tools._ErrorLogLevel = 4;
  9220. Tools._LogCache = "";
  9221. Tools.errorsCount = 0;
  9222. Tools.Log = Tools._LogEnabled;
  9223. Tools.Warn = Tools._WarnEnabled;
  9224. Tools.Error = Tools._ErrorEnabled;
  9225. // Performances
  9226. Tools._PerformanceNoneLogLevel = 0;
  9227. Tools._PerformanceUserMarkLogLevel = 1;
  9228. Tools._PerformanceConsoleLogLevel = 2;
  9229. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9230. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9231. return Tools;
  9232. }());
  9233. BABYLON.Tools = Tools;
  9234. /**
  9235. * This class is used to track a performance counter which is number based.
  9236. * The user has access to many properties which give statistics of different nature
  9237. *
  9238. * The implementer can track two kinds of Performance Counter: time and count
  9239. * 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.
  9240. * 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.
  9241. */
  9242. var PerfCounter = /** @class */ (function () {
  9243. function PerfCounter() {
  9244. this._startMonitoringTime = 0;
  9245. this._min = 0;
  9246. this._max = 0;
  9247. this._average = 0;
  9248. this._lastSecAverage = 0;
  9249. this._current = 0;
  9250. this._totalValueCount = 0;
  9251. this._totalAccumulated = 0;
  9252. this._lastSecAccumulated = 0;
  9253. this._lastSecTime = 0;
  9254. this._lastSecValueCount = 0;
  9255. }
  9256. Object.defineProperty(PerfCounter.prototype, "min", {
  9257. /**
  9258. * Returns the smallest value ever
  9259. */
  9260. get: function () {
  9261. return this._min;
  9262. },
  9263. enumerable: true,
  9264. configurable: true
  9265. });
  9266. Object.defineProperty(PerfCounter.prototype, "max", {
  9267. /**
  9268. * Returns the biggest value ever
  9269. */
  9270. get: function () {
  9271. return this._max;
  9272. },
  9273. enumerable: true,
  9274. configurable: true
  9275. });
  9276. Object.defineProperty(PerfCounter.prototype, "average", {
  9277. /**
  9278. * Returns the average value since the performance counter is running
  9279. */
  9280. get: function () {
  9281. return this._average;
  9282. },
  9283. enumerable: true,
  9284. configurable: true
  9285. });
  9286. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9287. /**
  9288. * Returns the average value of the last second the counter was monitored
  9289. */
  9290. get: function () {
  9291. return this._lastSecAverage;
  9292. },
  9293. enumerable: true,
  9294. configurable: true
  9295. });
  9296. Object.defineProperty(PerfCounter.prototype, "current", {
  9297. /**
  9298. * Returns the current value
  9299. */
  9300. get: function () {
  9301. return this._current;
  9302. },
  9303. enumerable: true,
  9304. configurable: true
  9305. });
  9306. Object.defineProperty(PerfCounter.prototype, "total", {
  9307. get: function () {
  9308. return this._totalAccumulated;
  9309. },
  9310. enumerable: true,
  9311. configurable: true
  9312. });
  9313. Object.defineProperty(PerfCounter.prototype, "count", {
  9314. get: function () {
  9315. return this._totalValueCount;
  9316. },
  9317. enumerable: true,
  9318. configurable: true
  9319. });
  9320. /**
  9321. * Call this method to start monitoring a new frame.
  9322. * 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.
  9323. */
  9324. PerfCounter.prototype.fetchNewFrame = function () {
  9325. this._totalValueCount++;
  9326. this._current = 0;
  9327. this._lastSecValueCount++;
  9328. };
  9329. /**
  9330. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9331. * @param newCount the count value to add to the monitored count
  9332. * @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.
  9333. */
  9334. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9335. if (!PerfCounter.Enabled) {
  9336. return;
  9337. }
  9338. this._current += newCount;
  9339. if (fetchResult) {
  9340. this._fetchResult();
  9341. }
  9342. };
  9343. /**
  9344. * Start monitoring this performance counter
  9345. */
  9346. PerfCounter.prototype.beginMonitoring = function () {
  9347. if (!PerfCounter.Enabled) {
  9348. return;
  9349. }
  9350. this._startMonitoringTime = Tools.Now;
  9351. };
  9352. /**
  9353. * Compute the time lapsed since the previous beginMonitoring() call.
  9354. * @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
  9355. */
  9356. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9357. if (newFrame === void 0) { newFrame = true; }
  9358. if (!PerfCounter.Enabled) {
  9359. return;
  9360. }
  9361. if (newFrame) {
  9362. this.fetchNewFrame();
  9363. }
  9364. var currentTime = Tools.Now;
  9365. this._current = currentTime - this._startMonitoringTime;
  9366. if (newFrame) {
  9367. this._fetchResult();
  9368. }
  9369. };
  9370. PerfCounter.prototype._fetchResult = function () {
  9371. this._totalAccumulated += this._current;
  9372. this._lastSecAccumulated += this._current;
  9373. // Min/Max update
  9374. this._min = Math.min(this._min, this._current);
  9375. this._max = Math.max(this._max, this._current);
  9376. this._average = this._totalAccumulated / this._totalValueCount;
  9377. // Reset last sec?
  9378. var now = Tools.Now;
  9379. if ((now - this._lastSecTime) > 1000) {
  9380. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9381. this._lastSecTime = now;
  9382. this._lastSecAccumulated = 0;
  9383. this._lastSecValueCount = 0;
  9384. }
  9385. };
  9386. PerfCounter.Enabled = true;
  9387. return PerfCounter;
  9388. }());
  9389. BABYLON.PerfCounter = PerfCounter;
  9390. /**
  9391. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9392. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9393. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9394. * @param name The name of the class, case should be preserved
  9395. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9396. */
  9397. function className(name, module) {
  9398. return function (target) {
  9399. target["__bjsclassName__"] = name;
  9400. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9401. };
  9402. }
  9403. BABYLON.className = className;
  9404. /**
  9405. * An implementation of a loop for asynchronous functions.
  9406. */
  9407. var AsyncLoop = /** @class */ (function () {
  9408. /**
  9409. * Constroctor.
  9410. * @param iterations the number of iterations.
  9411. * @param _fn the function to run each iteration
  9412. * @param _successCallback the callback that will be called upon succesful execution
  9413. * @param offset starting offset.
  9414. */
  9415. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9416. if (offset === void 0) { offset = 0; }
  9417. this.iterations = iterations;
  9418. this._fn = _fn;
  9419. this._successCallback = _successCallback;
  9420. this.index = offset - 1;
  9421. this._done = false;
  9422. }
  9423. /**
  9424. * Execute the next iteration. Must be called after the last iteration was finished.
  9425. */
  9426. AsyncLoop.prototype.executeNext = function () {
  9427. if (!this._done) {
  9428. if (this.index + 1 < this.iterations) {
  9429. ++this.index;
  9430. this._fn(this);
  9431. }
  9432. else {
  9433. this.breakLoop();
  9434. }
  9435. }
  9436. };
  9437. /**
  9438. * Break the loop and run the success callback.
  9439. */
  9440. AsyncLoop.prototype.breakLoop = function () {
  9441. this._done = true;
  9442. this._successCallback();
  9443. };
  9444. /**
  9445. * Helper function
  9446. */
  9447. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9448. if (offset === void 0) { offset = 0; }
  9449. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9450. loop.executeNext();
  9451. return loop;
  9452. };
  9453. /**
  9454. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9455. * @param iterations total number of iterations
  9456. * @param syncedIterations number of synchronous iterations in each async iteration.
  9457. * @param fn the function to call each iteration.
  9458. * @param callback a success call back that will be called when iterating stops.
  9459. * @param breakFunction a break condition (optional)
  9460. * @param timeout timeout settings for the setTimeout function. default - 0.
  9461. * @constructor
  9462. */
  9463. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9464. if (timeout === void 0) { timeout = 0; }
  9465. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9466. if (breakFunction && breakFunction())
  9467. loop.breakLoop();
  9468. else {
  9469. setTimeout(function () {
  9470. for (var i = 0; i < syncedIterations; ++i) {
  9471. var iteration = (loop.index * syncedIterations) + i;
  9472. if (iteration >= iterations)
  9473. break;
  9474. fn(iteration);
  9475. if (breakFunction && breakFunction()) {
  9476. loop.breakLoop();
  9477. break;
  9478. }
  9479. }
  9480. loop.executeNext();
  9481. }, timeout);
  9482. }
  9483. }, callback);
  9484. };
  9485. return AsyncLoop;
  9486. }());
  9487. BABYLON.AsyncLoop = AsyncLoop;
  9488. })(BABYLON || (BABYLON = {}));
  9489. //# sourceMappingURL=babylon.tools.js.map
  9490. "use strict";
  9491. var BABYLON;
  9492. (function (BABYLON) {
  9493. var PromiseStates;
  9494. (function (PromiseStates) {
  9495. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9496. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9497. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9498. })(PromiseStates || (PromiseStates = {}));
  9499. var FulFillmentAgregator = /** @class */ (function () {
  9500. function FulFillmentAgregator() {
  9501. this.count = 0;
  9502. this.target = 0;
  9503. this.results = [];
  9504. }
  9505. return FulFillmentAgregator;
  9506. }());
  9507. var InternalPromise = /** @class */ (function () {
  9508. function InternalPromise(resolver) {
  9509. var _this = this;
  9510. this._state = PromiseStates.Pending;
  9511. this._children = new Array();
  9512. this._rejectWasConsumed = false;
  9513. if (!resolver) {
  9514. return;
  9515. }
  9516. try {
  9517. resolver(function (value) {
  9518. _this._resolve(value);
  9519. }, function (reason) {
  9520. _this._reject(reason);
  9521. });
  9522. }
  9523. catch (e) {
  9524. this._reject(e);
  9525. }
  9526. }
  9527. InternalPromise.prototype.catch = function (onRejected) {
  9528. return this.then(undefined, onRejected);
  9529. };
  9530. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9531. var _this = this;
  9532. var newPromise = new InternalPromise();
  9533. newPromise._onFulfilled = onFulfilled;
  9534. newPromise._onRejected = onRejected;
  9535. // Composition
  9536. this._children.push(newPromise);
  9537. if (this._state !== PromiseStates.Pending) {
  9538. BABYLON.Tools.SetImmediate(function () {
  9539. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9540. var returnedValue = newPromise._resolve(_this._result);
  9541. if (returnedValue !== undefined && returnedValue !== null) {
  9542. if (returnedValue._state !== undefined) {
  9543. var returnedPromise = returnedValue;
  9544. newPromise._children.push(returnedPromise);
  9545. newPromise = returnedPromise;
  9546. }
  9547. else {
  9548. newPromise._result = returnedValue;
  9549. }
  9550. }
  9551. }
  9552. else {
  9553. newPromise._reject(_this._reason);
  9554. }
  9555. });
  9556. }
  9557. return newPromise;
  9558. };
  9559. InternalPromise.prototype._moveChildren = function (children) {
  9560. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9561. if (this._state === PromiseStates.Fulfilled) {
  9562. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9563. var child = _b[_i];
  9564. child._resolve(this._result);
  9565. }
  9566. }
  9567. else if (this._state === PromiseStates.Rejected) {
  9568. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9569. var child = _d[_c];
  9570. child._reject(this._reason);
  9571. }
  9572. }
  9573. var _a;
  9574. };
  9575. InternalPromise.prototype._resolve = function (value) {
  9576. try {
  9577. this._state = PromiseStates.Fulfilled;
  9578. var returnedValue = null;
  9579. if (this._onFulfilled) {
  9580. returnedValue = this._onFulfilled(value);
  9581. }
  9582. if (returnedValue !== undefined && returnedValue !== null) {
  9583. if (returnedValue._state !== undefined) {
  9584. // Transmit children
  9585. var returnedPromise = returnedValue;
  9586. returnedPromise._moveChildren(this._children);
  9587. value = returnedPromise._result;
  9588. }
  9589. else {
  9590. value = returnedValue;
  9591. }
  9592. }
  9593. this._result = value;
  9594. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9595. var child = _a[_i];
  9596. child._resolve(value);
  9597. }
  9598. this._children.length = 0;
  9599. delete this._onFulfilled;
  9600. delete this._onRejected;
  9601. }
  9602. catch (e) {
  9603. this._reject(e, true);
  9604. }
  9605. };
  9606. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9607. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9608. this._state = PromiseStates.Rejected;
  9609. this._reason = reason;
  9610. if (this._onRejected && !onLocalThrow) {
  9611. try {
  9612. this._onRejected(reason);
  9613. this._rejectWasConsumed = true;
  9614. }
  9615. catch (e) {
  9616. reason = e;
  9617. }
  9618. }
  9619. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9620. var child = _a[_i];
  9621. if (this._rejectWasConsumed) {
  9622. child._resolve(null);
  9623. }
  9624. else {
  9625. child._reject(reason);
  9626. }
  9627. }
  9628. this._children.length = 0;
  9629. delete this._onFulfilled;
  9630. delete this._onRejected;
  9631. };
  9632. InternalPromise.resolve = function (value) {
  9633. var newPromise = new InternalPromise();
  9634. newPromise._resolve(value);
  9635. return newPromise;
  9636. };
  9637. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9638. promise.then(function (value) {
  9639. agregator.results[index] = value;
  9640. agregator.count++;
  9641. if (agregator.count === agregator.target) {
  9642. agregator.rootPromise._resolve(agregator.results);
  9643. }
  9644. return null;
  9645. }, function (reason) {
  9646. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9647. agregator.rootPromise._reject(reason);
  9648. }
  9649. });
  9650. };
  9651. InternalPromise.all = function (promises) {
  9652. var newPromise = new InternalPromise();
  9653. var agregator = new FulFillmentAgregator();
  9654. agregator.target = promises.length;
  9655. agregator.rootPromise = newPromise;
  9656. if (promises.length) {
  9657. for (var index = 0; index < promises.length; index++) {
  9658. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9659. }
  9660. }
  9661. else {
  9662. newPromise._resolve([]);
  9663. }
  9664. return newPromise;
  9665. };
  9666. InternalPromise.race = function (promises) {
  9667. var newPromise = new InternalPromise();
  9668. if (promises.length) {
  9669. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9670. var promise = promises_1[_i];
  9671. promise.then(function (value) {
  9672. if (newPromise) {
  9673. newPromise._resolve(value);
  9674. newPromise = null;
  9675. }
  9676. return null;
  9677. }, function (reason) {
  9678. if (newPromise) {
  9679. newPromise._reject(reason);
  9680. newPromise = null;
  9681. }
  9682. });
  9683. }
  9684. }
  9685. return newPromise;
  9686. };
  9687. return InternalPromise;
  9688. }());
  9689. /**
  9690. * Helper class that provides a small promise polyfill
  9691. */
  9692. var PromisePolyfill = /** @class */ (function () {
  9693. function PromisePolyfill() {
  9694. }
  9695. /**
  9696. * Static function used to check if the polyfill is required
  9697. * If this is the case then the function will inject the polyfill to window.Promise
  9698. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9699. */
  9700. PromisePolyfill.Apply = function (force) {
  9701. if (force === void 0) { force = false; }
  9702. if (force || typeof Promise === 'undefined') {
  9703. var root = window;
  9704. root.Promise = InternalPromise;
  9705. }
  9706. };
  9707. return PromisePolyfill;
  9708. }());
  9709. BABYLON.PromisePolyfill = PromisePolyfill;
  9710. })(BABYLON || (BABYLON = {}));
  9711. //# sourceMappingURL=babylon.promise.js.map
  9712. "use strict";
  9713. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9714. var BABYLON;
  9715. (function (BABYLON) {
  9716. /**
  9717. * Helper class to push actions to a pool of workers.
  9718. */
  9719. var WorkerPool = /** @class */ (function () {
  9720. /**
  9721. * Constructor
  9722. * @param workers Array of workers to use for actions
  9723. */
  9724. function WorkerPool(workers) {
  9725. this._pendingActions = new Array();
  9726. this._workerInfos = workers.map(function (worker) { return ({
  9727. worker: worker,
  9728. active: false
  9729. }); });
  9730. }
  9731. /**
  9732. * Terminates all workers and clears any pending actions.
  9733. */
  9734. WorkerPool.prototype.dispose = function () {
  9735. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9736. var workerInfo = _a[_i];
  9737. workerInfo.worker.terminate();
  9738. }
  9739. delete this._workerInfos;
  9740. delete this._pendingActions;
  9741. };
  9742. /**
  9743. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9744. * pended until a worker has completed its action.
  9745. * @param action The action to perform. Call onComplete when the action is complete.
  9746. */
  9747. WorkerPool.prototype.push = function (action) {
  9748. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9749. var workerInfo = _a[_i];
  9750. if (!workerInfo.active) {
  9751. this._execute(workerInfo, action);
  9752. return;
  9753. }
  9754. }
  9755. this._pendingActions.push(action);
  9756. };
  9757. WorkerPool.prototype._execute = function (workerInfo, action) {
  9758. var _this = this;
  9759. workerInfo.active = true;
  9760. action(workerInfo.worker, function () {
  9761. workerInfo.active = false;
  9762. var nextAction = _this._pendingActions.shift();
  9763. if (nextAction) {
  9764. _this._execute(workerInfo, nextAction);
  9765. }
  9766. });
  9767. };
  9768. return WorkerPool;
  9769. }());
  9770. BABYLON.WorkerPool = WorkerPool;
  9771. })(BABYLON || (BABYLON = {}));
  9772. //# sourceMappingURL=babylon.workerPool.js.map
  9773. "use strict";
  9774. var BABYLON;
  9775. (function (BABYLON) {
  9776. var _AlphaState = /** @class */ (function () {
  9777. /**
  9778. * Initializes the state.
  9779. */
  9780. function _AlphaState() {
  9781. this._isAlphaBlendDirty = false;
  9782. this._isBlendFunctionParametersDirty = false;
  9783. this._isBlendEquationParametersDirty = false;
  9784. this._isBlendConstantsDirty = false;
  9785. this._alphaBlend = false;
  9786. this._blendFunctionParameters = new Array(4);
  9787. this._blendEquationParameters = new Array(2);
  9788. this._blendConstants = new Array(4);
  9789. this.reset();
  9790. }
  9791. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9792. get: function () {
  9793. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9799. get: function () {
  9800. return this._alphaBlend;
  9801. },
  9802. set: function (value) {
  9803. if (this._alphaBlend === value) {
  9804. return;
  9805. }
  9806. this._alphaBlend = value;
  9807. this._isAlphaBlendDirty = true;
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9813. if (this._blendConstants[0] === r &&
  9814. this._blendConstants[1] === g &&
  9815. this._blendConstants[2] === b &&
  9816. this._blendConstants[3] === a) {
  9817. return;
  9818. }
  9819. this._blendConstants[0] = r;
  9820. this._blendConstants[1] = g;
  9821. this._blendConstants[2] = b;
  9822. this._blendConstants[3] = a;
  9823. this._isBlendConstantsDirty = true;
  9824. };
  9825. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9826. if (this._blendFunctionParameters[0] === value0 &&
  9827. this._blendFunctionParameters[1] === value1 &&
  9828. this._blendFunctionParameters[2] === value2 &&
  9829. this._blendFunctionParameters[3] === value3) {
  9830. return;
  9831. }
  9832. this._blendFunctionParameters[0] = value0;
  9833. this._blendFunctionParameters[1] = value1;
  9834. this._blendFunctionParameters[2] = value2;
  9835. this._blendFunctionParameters[3] = value3;
  9836. this._isBlendFunctionParametersDirty = true;
  9837. };
  9838. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9839. if (this._blendEquationParameters[0] === rgb &&
  9840. this._blendEquationParameters[1] === alpha) {
  9841. return;
  9842. }
  9843. this._blendEquationParameters[0] = rgb;
  9844. this._blendEquationParameters[1] = alpha;
  9845. this._isBlendEquationParametersDirty = true;
  9846. };
  9847. _AlphaState.prototype.reset = function () {
  9848. this._alphaBlend = false;
  9849. this._blendFunctionParameters[0] = null;
  9850. this._blendFunctionParameters[1] = null;
  9851. this._blendFunctionParameters[2] = null;
  9852. this._blendFunctionParameters[3] = null;
  9853. this._blendEquationParameters[0] = null;
  9854. this._blendEquationParameters[1] = null;
  9855. this._blendConstants[0] = null;
  9856. this._blendConstants[1] = null;
  9857. this._blendConstants[2] = null;
  9858. this._blendConstants[3] = null;
  9859. this._isAlphaBlendDirty = true;
  9860. this._isBlendFunctionParametersDirty = false;
  9861. this._isBlendEquationParametersDirty = false;
  9862. this._isBlendConstantsDirty = false;
  9863. };
  9864. _AlphaState.prototype.apply = function (gl) {
  9865. if (!this.isDirty) {
  9866. return;
  9867. }
  9868. // Alpha blend
  9869. if (this._isAlphaBlendDirty) {
  9870. if (this._alphaBlend) {
  9871. gl.enable(gl.BLEND);
  9872. }
  9873. else {
  9874. gl.disable(gl.BLEND);
  9875. }
  9876. this._isAlphaBlendDirty = false;
  9877. }
  9878. // Alpha function
  9879. if (this._isBlendFunctionParametersDirty) {
  9880. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9881. this._isBlendFunctionParametersDirty = false;
  9882. }
  9883. // Alpha equation
  9884. if (this._isBlendEquationParametersDirty) {
  9885. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9886. this._isBlendEquationParametersDirty = false;
  9887. }
  9888. // Constants
  9889. if (this._isBlendConstantsDirty) {
  9890. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9891. this._isBlendConstantsDirty = false;
  9892. }
  9893. };
  9894. return _AlphaState;
  9895. }());
  9896. BABYLON._AlphaState = _AlphaState;
  9897. })(BABYLON || (BABYLON = {}));
  9898. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9899. "use strict";
  9900. var BABYLON;
  9901. (function (BABYLON) {
  9902. var _DepthCullingState = /** @class */ (function () {
  9903. /**
  9904. * Initializes the state.
  9905. */
  9906. function _DepthCullingState() {
  9907. this._isDepthTestDirty = false;
  9908. this._isDepthMaskDirty = false;
  9909. this._isDepthFuncDirty = false;
  9910. this._isCullFaceDirty = false;
  9911. this._isCullDirty = false;
  9912. this._isZOffsetDirty = false;
  9913. this._isFrontFaceDirty = false;
  9914. this.reset();
  9915. }
  9916. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9917. get: function () {
  9918. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9924. get: function () {
  9925. return this._zOffset;
  9926. },
  9927. set: function (value) {
  9928. if (this._zOffset === value) {
  9929. return;
  9930. }
  9931. this._zOffset = value;
  9932. this._isZOffsetDirty = true;
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9938. get: function () {
  9939. return this._cullFace;
  9940. },
  9941. set: function (value) {
  9942. if (this._cullFace === value) {
  9943. return;
  9944. }
  9945. this._cullFace = value;
  9946. this._isCullFaceDirty = true;
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9952. get: function () {
  9953. return this._cull;
  9954. },
  9955. set: function (value) {
  9956. if (this._cull === value) {
  9957. return;
  9958. }
  9959. this._cull = value;
  9960. this._isCullDirty = true;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9966. get: function () {
  9967. return this._depthFunc;
  9968. },
  9969. set: function (value) {
  9970. if (this._depthFunc === value) {
  9971. return;
  9972. }
  9973. this._depthFunc = value;
  9974. this._isDepthFuncDirty = true;
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9980. get: function () {
  9981. return this._depthMask;
  9982. },
  9983. set: function (value) {
  9984. if (this._depthMask === value) {
  9985. return;
  9986. }
  9987. this._depthMask = value;
  9988. this._isDepthMaskDirty = true;
  9989. },
  9990. enumerable: true,
  9991. configurable: true
  9992. });
  9993. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9994. get: function () {
  9995. return this._depthTest;
  9996. },
  9997. set: function (value) {
  9998. if (this._depthTest === value) {
  9999. return;
  10000. }
  10001. this._depthTest = value;
  10002. this._isDepthTestDirty = true;
  10003. },
  10004. enumerable: true,
  10005. configurable: true
  10006. });
  10007. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10008. get: function () {
  10009. return this._frontFace;
  10010. },
  10011. set: function (value) {
  10012. if (this._frontFace === value) {
  10013. return;
  10014. }
  10015. this._frontFace = value;
  10016. this._isFrontFaceDirty = true;
  10017. },
  10018. enumerable: true,
  10019. configurable: true
  10020. });
  10021. _DepthCullingState.prototype.reset = function () {
  10022. this._depthMask = true;
  10023. this._depthTest = true;
  10024. this._depthFunc = null;
  10025. this._cullFace = null;
  10026. this._cull = null;
  10027. this._zOffset = 0;
  10028. this._frontFace = null;
  10029. this._isDepthTestDirty = true;
  10030. this._isDepthMaskDirty = true;
  10031. this._isDepthFuncDirty = false;
  10032. this._isCullFaceDirty = false;
  10033. this._isCullDirty = false;
  10034. this._isZOffsetDirty = false;
  10035. this._isFrontFaceDirty = false;
  10036. };
  10037. _DepthCullingState.prototype.apply = function (gl) {
  10038. if (!this.isDirty) {
  10039. return;
  10040. }
  10041. // Cull
  10042. if (this._isCullDirty) {
  10043. if (this.cull) {
  10044. gl.enable(gl.CULL_FACE);
  10045. }
  10046. else {
  10047. gl.disable(gl.CULL_FACE);
  10048. }
  10049. this._isCullDirty = false;
  10050. }
  10051. // Cull face
  10052. if (this._isCullFaceDirty) {
  10053. gl.cullFace(this.cullFace);
  10054. this._isCullFaceDirty = false;
  10055. }
  10056. // Depth mask
  10057. if (this._isDepthMaskDirty) {
  10058. gl.depthMask(this.depthMask);
  10059. this._isDepthMaskDirty = false;
  10060. }
  10061. // Depth test
  10062. if (this._isDepthTestDirty) {
  10063. if (this.depthTest) {
  10064. gl.enable(gl.DEPTH_TEST);
  10065. }
  10066. else {
  10067. gl.disable(gl.DEPTH_TEST);
  10068. }
  10069. this._isDepthTestDirty = false;
  10070. }
  10071. // Depth func
  10072. if (this._isDepthFuncDirty) {
  10073. gl.depthFunc(this.depthFunc);
  10074. this._isDepthFuncDirty = false;
  10075. }
  10076. // zOffset
  10077. if (this._isZOffsetDirty) {
  10078. if (this.zOffset) {
  10079. gl.enable(gl.POLYGON_OFFSET_FILL);
  10080. gl.polygonOffset(this.zOffset, 0);
  10081. }
  10082. else {
  10083. gl.disable(gl.POLYGON_OFFSET_FILL);
  10084. }
  10085. this._isZOffsetDirty = false;
  10086. }
  10087. // Front face
  10088. if (this._isFrontFaceDirty) {
  10089. gl.frontFace(this.frontFace);
  10090. this._isFrontFaceDirty = false;
  10091. }
  10092. };
  10093. return _DepthCullingState;
  10094. }());
  10095. BABYLON._DepthCullingState = _DepthCullingState;
  10096. })(BABYLON || (BABYLON = {}));
  10097. //# sourceMappingURL=babylon.depthCullingState.js.map
  10098. "use strict";
  10099. var BABYLON;
  10100. (function (BABYLON) {
  10101. var _StencilState = /** @class */ (function () {
  10102. function _StencilState() {
  10103. this._isStencilTestDirty = false;
  10104. this._isStencilMaskDirty = false;
  10105. this._isStencilFuncDirty = false;
  10106. this._isStencilOpDirty = false;
  10107. this.reset();
  10108. }
  10109. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10110. get: function () {
  10111. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10112. },
  10113. enumerable: true,
  10114. configurable: true
  10115. });
  10116. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10117. get: function () {
  10118. return this._stencilFunc;
  10119. },
  10120. set: function (value) {
  10121. if (this._stencilFunc === value) {
  10122. return;
  10123. }
  10124. this._stencilFunc = value;
  10125. this._isStencilFuncDirty = true;
  10126. },
  10127. enumerable: true,
  10128. configurable: true
  10129. });
  10130. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10131. get: function () {
  10132. return this._stencilFuncRef;
  10133. },
  10134. set: function (value) {
  10135. if (this._stencilFuncRef === value) {
  10136. return;
  10137. }
  10138. this._stencilFuncRef = value;
  10139. this._isStencilFuncDirty = true;
  10140. },
  10141. enumerable: true,
  10142. configurable: true
  10143. });
  10144. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10145. get: function () {
  10146. return this._stencilFuncMask;
  10147. },
  10148. set: function (value) {
  10149. if (this._stencilFuncMask === value) {
  10150. return;
  10151. }
  10152. this._stencilFuncMask = value;
  10153. this._isStencilFuncDirty = true;
  10154. },
  10155. enumerable: true,
  10156. configurable: true
  10157. });
  10158. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10159. get: function () {
  10160. return this._stencilOpStencilFail;
  10161. },
  10162. set: function (value) {
  10163. if (this._stencilOpStencilFail === value) {
  10164. return;
  10165. }
  10166. this._stencilOpStencilFail = value;
  10167. this._isStencilOpDirty = true;
  10168. },
  10169. enumerable: true,
  10170. configurable: true
  10171. });
  10172. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10173. get: function () {
  10174. return this._stencilOpDepthFail;
  10175. },
  10176. set: function (value) {
  10177. if (this._stencilOpDepthFail === value) {
  10178. return;
  10179. }
  10180. this._stencilOpDepthFail = value;
  10181. this._isStencilOpDirty = true;
  10182. },
  10183. enumerable: true,
  10184. configurable: true
  10185. });
  10186. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10187. get: function () {
  10188. return this._stencilOpStencilDepthPass;
  10189. },
  10190. set: function (value) {
  10191. if (this._stencilOpStencilDepthPass === value) {
  10192. return;
  10193. }
  10194. this._stencilOpStencilDepthPass = value;
  10195. this._isStencilOpDirty = true;
  10196. },
  10197. enumerable: true,
  10198. configurable: true
  10199. });
  10200. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10201. get: function () {
  10202. return this._stencilMask;
  10203. },
  10204. set: function (value) {
  10205. if (this._stencilMask === value) {
  10206. return;
  10207. }
  10208. this._stencilMask = value;
  10209. this._isStencilMaskDirty = true;
  10210. },
  10211. enumerable: true,
  10212. configurable: true
  10213. });
  10214. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10215. get: function () {
  10216. return this._stencilTest;
  10217. },
  10218. set: function (value) {
  10219. if (this._stencilTest === value) {
  10220. return;
  10221. }
  10222. this._stencilTest = value;
  10223. this._isStencilTestDirty = true;
  10224. },
  10225. enumerable: true,
  10226. configurable: true
  10227. });
  10228. _StencilState.prototype.reset = function () {
  10229. this._stencilTest = false;
  10230. this._stencilMask = 0xFF;
  10231. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10232. this._stencilFuncRef = 1;
  10233. this._stencilFuncMask = 0xFF;
  10234. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10235. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10236. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10237. this._isStencilTestDirty = true;
  10238. this._isStencilMaskDirty = true;
  10239. this._isStencilFuncDirty = true;
  10240. this._isStencilOpDirty = true;
  10241. };
  10242. _StencilState.prototype.apply = function (gl) {
  10243. if (!this.isDirty) {
  10244. return;
  10245. }
  10246. // Stencil test
  10247. if (this._isStencilTestDirty) {
  10248. if (this.stencilTest) {
  10249. gl.enable(gl.STENCIL_TEST);
  10250. }
  10251. else {
  10252. gl.disable(gl.STENCIL_TEST);
  10253. }
  10254. this._isStencilTestDirty = false;
  10255. }
  10256. // Stencil mask
  10257. if (this._isStencilMaskDirty) {
  10258. gl.stencilMask(this.stencilMask);
  10259. this._isStencilMaskDirty = false;
  10260. }
  10261. // Stencil func
  10262. if (this._isStencilFuncDirty) {
  10263. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10264. this._isStencilFuncDirty = false;
  10265. }
  10266. // Stencil op
  10267. if (this._isStencilOpDirty) {
  10268. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10269. this._isStencilOpDirty = false;
  10270. }
  10271. };
  10272. return _StencilState;
  10273. }());
  10274. BABYLON._StencilState = _StencilState;
  10275. })(BABYLON || (BABYLON = {}));
  10276. //# sourceMappingURL=babylon.stencilState.js.map
  10277. "use strict";
  10278. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10279. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10280. s = arguments[i];
  10281. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10282. t[p] = s[p];
  10283. }
  10284. return t;
  10285. };
  10286. var BABYLON;
  10287. (function (BABYLON) {
  10288. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10289. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10290. };
  10291. var compileRawShader = function (gl, source, type) {
  10292. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10293. gl.shaderSource(shader, source);
  10294. gl.compileShader(shader);
  10295. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10296. var log = gl.getShaderInfoLog(shader);
  10297. if (log) {
  10298. throw new Error(log);
  10299. }
  10300. }
  10301. if (!shader) {
  10302. throw new Error("Something went wrong while compile the shader.");
  10303. }
  10304. return shader;
  10305. };
  10306. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10307. var magFilter = gl.NEAREST;
  10308. var minFilter = gl.NEAREST;
  10309. switch (samplingMode) {
  10310. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10311. magFilter = gl.LINEAR;
  10312. if (generateMipMaps) {
  10313. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10314. }
  10315. else {
  10316. minFilter = gl.LINEAR;
  10317. }
  10318. break;
  10319. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10320. magFilter = gl.LINEAR;
  10321. if (generateMipMaps) {
  10322. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10323. }
  10324. else {
  10325. minFilter = gl.LINEAR;
  10326. }
  10327. break;
  10328. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10329. magFilter = gl.NEAREST;
  10330. if (generateMipMaps) {
  10331. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10332. }
  10333. else {
  10334. minFilter = gl.NEAREST;
  10335. }
  10336. break;
  10337. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10338. magFilter = gl.NEAREST;
  10339. if (generateMipMaps) {
  10340. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10341. }
  10342. else {
  10343. minFilter = gl.NEAREST;
  10344. }
  10345. break;
  10346. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10347. magFilter = gl.NEAREST;
  10348. if (generateMipMaps) {
  10349. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10350. }
  10351. else {
  10352. minFilter = gl.LINEAR;
  10353. }
  10354. break;
  10355. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10356. magFilter = gl.NEAREST;
  10357. if (generateMipMaps) {
  10358. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10359. }
  10360. else {
  10361. minFilter = gl.LINEAR;
  10362. }
  10363. break;
  10364. case BABYLON.Texture.NEAREST_LINEAR:
  10365. magFilter = gl.NEAREST;
  10366. minFilter = gl.LINEAR;
  10367. break;
  10368. case BABYLON.Texture.NEAREST_NEAREST:
  10369. magFilter = gl.NEAREST;
  10370. minFilter = gl.NEAREST;
  10371. break;
  10372. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10373. magFilter = gl.LINEAR;
  10374. if (generateMipMaps) {
  10375. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10376. }
  10377. else {
  10378. minFilter = gl.NEAREST;
  10379. }
  10380. break;
  10381. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10382. magFilter = gl.LINEAR;
  10383. if (generateMipMaps) {
  10384. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10385. }
  10386. else {
  10387. minFilter = gl.NEAREST;
  10388. }
  10389. break;
  10390. case BABYLON.Texture.LINEAR_LINEAR:
  10391. magFilter = gl.LINEAR;
  10392. minFilter = gl.LINEAR;
  10393. break;
  10394. case BABYLON.Texture.LINEAR_NEAREST:
  10395. magFilter = gl.LINEAR;
  10396. minFilter = gl.NEAREST;
  10397. break;
  10398. }
  10399. return {
  10400. min: minFilter,
  10401. mag: magFilter
  10402. };
  10403. };
  10404. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10405. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10406. var img;
  10407. var onload = function () {
  10408. loadedImages[index] = img;
  10409. loadedImages._internalCount++;
  10410. if (scene) {
  10411. scene._removePendingData(img);
  10412. }
  10413. if (loadedImages._internalCount === 6) {
  10414. onfinish(loadedImages);
  10415. }
  10416. };
  10417. var onerror = function (message, exception) {
  10418. if (scene) {
  10419. scene._removePendingData(img);
  10420. }
  10421. if (onErrorCallBack) {
  10422. onErrorCallBack(message, exception);
  10423. }
  10424. };
  10425. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10426. if (scene) {
  10427. scene._addPendingData(img);
  10428. }
  10429. };
  10430. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10431. if (onError === void 0) { onError = null; }
  10432. var loadedImages = [];
  10433. loadedImages._internalCount = 0;
  10434. for (var index = 0; index < 6; index++) {
  10435. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10436. }
  10437. };
  10438. var BufferPointer = /** @class */ (function () {
  10439. function BufferPointer() {
  10440. }
  10441. return BufferPointer;
  10442. }());
  10443. var InstancingAttributeInfo = /** @class */ (function () {
  10444. function InstancingAttributeInfo() {
  10445. }
  10446. return InstancingAttributeInfo;
  10447. }());
  10448. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10449. /**
  10450. * Define options used to create a render target texture
  10451. */
  10452. var RenderTargetCreationOptions = /** @class */ (function () {
  10453. function RenderTargetCreationOptions() {
  10454. }
  10455. return RenderTargetCreationOptions;
  10456. }());
  10457. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10458. /**
  10459. * Define options used to create a depth texture
  10460. */
  10461. var DepthTextureCreationOptions = /** @class */ (function () {
  10462. function DepthTextureCreationOptions() {
  10463. }
  10464. return DepthTextureCreationOptions;
  10465. }());
  10466. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10467. /**
  10468. * Regroup several parameters relative to the browser in use
  10469. */
  10470. var EngineCapabilities = /** @class */ (function () {
  10471. function EngineCapabilities() {
  10472. }
  10473. return EngineCapabilities;
  10474. }());
  10475. BABYLON.EngineCapabilities = EngineCapabilities;
  10476. /**
  10477. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10478. */
  10479. var Engine = /** @class */ (function () {
  10480. /**
  10481. * @constructor
  10482. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10483. * @param antialias defines enable antialiasing (default: false)
  10484. * @param options defines further options to be sent to the getContext() function
  10485. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10486. */
  10487. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10488. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10489. var _this = this;
  10490. // Public members
  10491. this.forcePOTTextures = false;
  10492. this.isFullscreen = false;
  10493. this.isPointerLock = false;
  10494. this.cullBackFaces = true;
  10495. this.renderEvenInBackground = true;
  10496. this.preventCacheWipeBetweenFrames = false;
  10497. /**
  10498. * To enable/disable IDB support and avoid XHR on .manifest
  10499. **/
  10500. this.enableOfflineSupport = false;
  10501. this.scenes = new Array();
  10502. this.postProcesses = new Array();
  10503. // Observables
  10504. /**
  10505. * Observable event triggered each time the rendering canvas is resized
  10506. */
  10507. this.onResizeObservable = new BABYLON.Observable();
  10508. /**
  10509. * Observable event triggered each time the canvas loses focus
  10510. */
  10511. this.onCanvasBlurObservable = new BABYLON.Observable();
  10512. /**
  10513. * Observable event triggered each time the canvas gains focus
  10514. */
  10515. this.onCanvasFocusObservable = new BABYLON.Observable();
  10516. /**
  10517. * Observable event triggered each time the canvas receives pointerout event
  10518. */
  10519. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10520. /**
  10521. * Observable event triggered before each texture is initialized
  10522. */
  10523. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10524. //WebVR
  10525. this._vrDisplay = undefined;
  10526. this._vrSupported = false;
  10527. this._vrExclusivePointerMode = false;
  10528. // Uniform buffers list
  10529. this.disableUniformBuffers = false;
  10530. this._uniformBuffers = new Array();
  10531. // Observables
  10532. /**
  10533. * Observable raised when the engine begins a new frame
  10534. */
  10535. this.onBeginFrameObservable = new BABYLON.Observable();
  10536. /**
  10537. * Observable raised when the engine ends the current frame
  10538. */
  10539. this.onEndFrameObservable = new BABYLON.Observable();
  10540. /**
  10541. * Observable raised when the engine is about to compile a shader
  10542. */
  10543. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10544. /**
  10545. * Observable raised when the engine has jsut compiled a shader
  10546. */
  10547. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10548. this._windowIsBackground = false;
  10549. this._webGLVersion = 1.0;
  10550. this._badOS = false;
  10551. this._badDesktopOS = false;
  10552. /**
  10553. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10554. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10555. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10556. */
  10557. this.disableTextureBindingOptimization = false;
  10558. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10559. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10560. this.onVRRequestPresentStart = new BABYLON.Observable();
  10561. this._colorWrite = true;
  10562. this._drawCalls = new BABYLON.PerfCounter();
  10563. this._textureCollisions = new BABYLON.PerfCounter();
  10564. this._renderingQueueLaunched = false;
  10565. this._activeRenderLoops = new Array();
  10566. // Deterministic lockstepMaxSteps
  10567. this._deterministicLockstep = false;
  10568. this._lockstepMaxSteps = 4;
  10569. // Lost context
  10570. this.onContextLostObservable = new BABYLON.Observable();
  10571. this.onContextRestoredObservable = new BABYLON.Observable();
  10572. this._contextWasLost = false;
  10573. this._doNotHandleContextLost = false;
  10574. // FPS
  10575. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10576. this._fps = 60;
  10577. this._deltaTime = 0;
  10578. /**
  10579. * Turn this value on if you want to pause FPS computation when in background
  10580. */
  10581. this.disablePerformanceMonitorInBackground = false;
  10582. // States
  10583. this._depthCullingState = new BABYLON._DepthCullingState();
  10584. this._stencilState = new BABYLON._StencilState();
  10585. this._alphaState = new BABYLON._AlphaState();
  10586. this._alphaMode = Engine.ALPHA_DISABLE;
  10587. // Cache
  10588. this._internalTexturesCache = new Array();
  10589. this._activeChannel = 0;
  10590. this._currentTextureChannel = -1;
  10591. this._boundTexturesCache = {};
  10592. this._compiledEffects = {};
  10593. this._vertexAttribArraysEnabled = [];
  10594. this._uintIndicesCurrentlySet = false;
  10595. this._currentBoundBuffer = new Array();
  10596. this._currentBufferPointers = new Array();
  10597. this._currentInstanceLocations = new Array();
  10598. this._currentInstanceBuffers = new Array();
  10599. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10600. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10601. this._vaoRecordInProgress = false;
  10602. this._mustWipeVertexAttributes = false;
  10603. this._nextFreeTextureSlots = new Array();
  10604. this._maxSimultaneousTextures = 0;
  10605. this._activeRequests = new Array();
  10606. // Hardware supported Compressed Textures
  10607. this._texturesSupported = new Array();
  10608. this._onVRFullScreenTriggered = function () {
  10609. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10610. //get the old size before we change
  10611. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10612. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10613. //get the width and height, change the render size
  10614. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10615. _this.setHardwareScalingLevel(1);
  10616. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10617. }
  10618. else {
  10619. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10620. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10621. }
  10622. };
  10623. this._boundUniforms = {};
  10624. // Register promises
  10625. BABYLON.PromisePolyfill.Apply();
  10626. var canvas = null;
  10627. Engine.Instances.push(this);
  10628. if (!canvasOrContext) {
  10629. return;
  10630. }
  10631. options = options || {};
  10632. if (canvasOrContext.getContext) {
  10633. canvas = canvasOrContext;
  10634. this._renderingCanvas = canvas;
  10635. if (antialias != null) {
  10636. options.antialias = antialias;
  10637. }
  10638. if (options.deterministicLockstep === undefined) {
  10639. options.deterministicLockstep = false;
  10640. }
  10641. if (options.lockstepMaxSteps === undefined) {
  10642. options.lockstepMaxSteps = 4;
  10643. }
  10644. if (options.preserveDrawingBuffer === undefined) {
  10645. options.preserveDrawingBuffer = false;
  10646. }
  10647. if (options.audioEngine === undefined) {
  10648. options.audioEngine = true;
  10649. }
  10650. if (options.stencil === undefined) {
  10651. options.stencil = true;
  10652. }
  10653. this._deterministicLockstep = options.deterministicLockstep;
  10654. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10655. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10656. // Exceptions
  10657. if (navigator && navigator.userAgent) {
  10658. var ua = navigator.userAgent;
  10659. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10660. var exception = _a[_i];
  10661. var key = exception.key;
  10662. var targets = exception.targets;
  10663. if (ua.indexOf(key) > -1) {
  10664. if (exception.capture && exception.captureConstraint) {
  10665. var capture = exception.capture;
  10666. var constraint = exception.captureConstraint;
  10667. var regex = new RegExp(capture);
  10668. var matches = regex.exec(ua);
  10669. if (matches && matches.length > 0) {
  10670. var capturedValue = parseInt(matches[matches.length - 1]);
  10671. if (capturedValue >= constraint) {
  10672. continue;
  10673. }
  10674. }
  10675. }
  10676. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10677. var target = targets_1[_b];
  10678. switch (target) {
  10679. case "uniformBuffer":
  10680. this.disableUniformBuffers = true;
  10681. break;
  10682. case "textureBindingOptimization":
  10683. this.disableTextureBindingOptimization = true;
  10684. break;
  10685. }
  10686. }
  10687. }
  10688. }
  10689. }
  10690. // GL
  10691. if (!options.disableWebGL2Support) {
  10692. try {
  10693. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10694. if (this._gl) {
  10695. this._webGLVersion = 2.0;
  10696. }
  10697. }
  10698. catch (e) {
  10699. // Do nothing
  10700. }
  10701. }
  10702. if (!this._gl) {
  10703. if (!canvas) {
  10704. throw new Error("The provided canvas is null or undefined.");
  10705. }
  10706. try {
  10707. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10708. }
  10709. catch (e) {
  10710. throw new Error("WebGL not supported");
  10711. }
  10712. }
  10713. if (!this._gl) {
  10714. throw new Error("WebGL not supported");
  10715. }
  10716. this._onCanvasFocus = function () {
  10717. _this.onCanvasFocusObservable.notifyObservers(_this);
  10718. };
  10719. this._onCanvasBlur = function () {
  10720. _this.onCanvasBlurObservable.notifyObservers(_this);
  10721. };
  10722. canvas.addEventListener("focus", this._onCanvasFocus);
  10723. canvas.addEventListener("blur", this._onCanvasBlur);
  10724. this._onBlur = function () {
  10725. if (_this.disablePerformanceMonitorInBackground) {
  10726. _this._performanceMonitor.disable();
  10727. }
  10728. _this._windowIsBackground = true;
  10729. };
  10730. this._onFocus = function () {
  10731. if (_this.disablePerformanceMonitorInBackground) {
  10732. _this._performanceMonitor.enable();
  10733. }
  10734. _this._windowIsBackground = false;
  10735. };
  10736. this._onCanvasPointerOut = function (ev) {
  10737. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10738. };
  10739. window.addEventListener("blur", this._onBlur);
  10740. window.addEventListener("focus", this._onFocus);
  10741. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10742. // Context lost
  10743. if (!this._doNotHandleContextLost) {
  10744. this._onContextLost = function (evt) {
  10745. evt.preventDefault();
  10746. _this._contextWasLost = true;
  10747. BABYLON.Tools.Warn("WebGL context lost.");
  10748. _this.onContextLostObservable.notifyObservers(_this);
  10749. };
  10750. this._onContextRestored = function (evt) {
  10751. // Adding a timeout to avoid race condition at browser level
  10752. setTimeout(function () {
  10753. // Rebuild gl context
  10754. _this._initGLContext();
  10755. // Rebuild effects
  10756. _this._rebuildEffects();
  10757. // Rebuild textures
  10758. _this._rebuildInternalTextures();
  10759. // Rebuild buffers
  10760. _this._rebuildBuffers();
  10761. // Cache
  10762. _this.wipeCaches(true);
  10763. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10764. _this.onContextRestoredObservable.notifyObservers(_this);
  10765. _this._contextWasLost = false;
  10766. }, 0);
  10767. };
  10768. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10769. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10770. }
  10771. }
  10772. else {
  10773. this._gl = canvasOrContext;
  10774. this._renderingCanvas = this._gl.canvas;
  10775. if (this._gl.renderbufferStorageMultisample) {
  10776. this._webGLVersion = 2.0;
  10777. }
  10778. options.stencil = this._gl.getContextAttributes().stencil;
  10779. }
  10780. // Viewport
  10781. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10782. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10783. this.resize();
  10784. this._isStencilEnable = options.stencil ? true : false;
  10785. this._initGLContext();
  10786. if (canvas) {
  10787. // Fullscreen
  10788. this._onFullscreenChange = function () {
  10789. if (document.fullscreen !== undefined) {
  10790. _this.isFullscreen = document.fullscreen;
  10791. }
  10792. else if (document.mozFullScreen !== undefined) {
  10793. _this.isFullscreen = document.mozFullScreen;
  10794. }
  10795. else if (document.webkitIsFullScreen !== undefined) {
  10796. _this.isFullscreen = document.webkitIsFullScreen;
  10797. }
  10798. else if (document.msIsFullScreen !== undefined) {
  10799. _this.isFullscreen = document.msIsFullScreen;
  10800. }
  10801. // Pointer lock
  10802. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10803. canvas.requestPointerLock = canvas.requestPointerLock ||
  10804. canvas.msRequestPointerLock ||
  10805. canvas.mozRequestPointerLock ||
  10806. canvas.webkitRequestPointerLock;
  10807. if (canvas.requestPointerLock) {
  10808. canvas.requestPointerLock();
  10809. }
  10810. }
  10811. };
  10812. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10813. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10814. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10815. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10816. // Pointer lock
  10817. this._onPointerLockChange = function () {
  10818. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10819. document.webkitPointerLockElement === canvas ||
  10820. document.msPointerLockElement === canvas ||
  10821. document.pointerLockElement === canvas);
  10822. };
  10823. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10824. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10825. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10826. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10827. this._onVRDisplayPointerRestricted = function () {
  10828. if (canvas) {
  10829. canvas.requestPointerLock();
  10830. }
  10831. };
  10832. this._onVRDisplayPointerUnrestricted = function () {
  10833. document.exitPointerLock();
  10834. };
  10835. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10836. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10837. }
  10838. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10839. Engine.audioEngine = new BABYLON.AudioEngine();
  10840. }
  10841. // Prepare buffer pointers
  10842. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10843. this._currentBufferPointers[i] = new BufferPointer();
  10844. }
  10845. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10846. // Load WebVR Devices
  10847. if (options.autoEnableWebVR) {
  10848. this.initWebVR();
  10849. }
  10850. // Detect if we are running on a faulty buggy OS.
  10851. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10852. // Detect if we are running on a faulty buggy desktop OS.
  10853. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10854. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10855. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10856. }
  10857. Object.defineProperty(Engine, "LastCreatedEngine", {
  10858. get: function () {
  10859. if (Engine.Instances.length === 0) {
  10860. return null;
  10861. }
  10862. return Engine.Instances[Engine.Instances.length - 1];
  10863. },
  10864. enumerable: true,
  10865. configurable: true
  10866. });
  10867. Object.defineProperty(Engine, "LastCreatedScene", {
  10868. get: function () {
  10869. var lastCreatedEngine = Engine.LastCreatedEngine;
  10870. if (!lastCreatedEngine) {
  10871. return null;
  10872. }
  10873. if (lastCreatedEngine.scenes.length === 0) {
  10874. return null;
  10875. }
  10876. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. /**
  10882. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10883. */
  10884. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10885. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10886. var engine = Engine.Instances[engineIndex];
  10887. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10888. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10889. }
  10890. }
  10891. };
  10892. Object.defineProperty(Engine, "NEVER", {
  10893. get: function () {
  10894. return Engine._NEVER;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine, "ALWAYS", {
  10900. get: function () {
  10901. return Engine._ALWAYS;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(Engine, "LESS", {
  10907. get: function () {
  10908. return Engine._LESS;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine, "EQUAL", {
  10914. get: function () {
  10915. return Engine._EQUAL;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine, "LEQUAL", {
  10921. get: function () {
  10922. return Engine._LEQUAL;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine, "GREATER", {
  10928. get: function () {
  10929. return Engine._GREATER;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine, "GEQUAL", {
  10935. get: function () {
  10936. return Engine._GEQUAL;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine, "NOTEQUAL", {
  10942. get: function () {
  10943. return Engine._NOTEQUAL;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(Engine, "KEEP", {
  10949. get: function () {
  10950. return Engine._KEEP;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(Engine, "REPLACE", {
  10956. get: function () {
  10957. return Engine._REPLACE;
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. Object.defineProperty(Engine, "INCR", {
  10963. get: function () {
  10964. return Engine._INCR;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(Engine, "DECR", {
  10970. get: function () {
  10971. return Engine._DECR;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(Engine, "INVERT", {
  10977. get: function () {
  10978. return Engine._INVERT;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(Engine, "INCR_WRAP", {
  10984. get: function () {
  10985. return Engine._INCR_WRAP;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine, "DECR_WRAP", {
  10991. get: function () {
  10992. return Engine._DECR_WRAP;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10998. get: function () {
  10999. return Engine._ALPHA_DISABLE;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11005. get: function () {
  11006. return Engine._ALPHA_ONEONE;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(Engine, "ALPHA_ADD", {
  11012. get: function () {
  11013. return Engine._ALPHA_ADD;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11019. get: function () {
  11020. return Engine._ALPHA_COMBINE;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11026. get: function () {
  11027. return Engine._ALPHA_SUBTRACT;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11033. get: function () {
  11034. return Engine._ALPHA_MULTIPLY;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11040. get: function () {
  11041. return Engine._ALPHA_MAXIMIZED;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11047. get: function () {
  11048. return Engine._ALPHA_PREMULTIPLIED;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11054. get: function () {
  11055. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11061. get: function () {
  11062. return Engine._ALPHA_INTERPOLATE;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11068. get: function () {
  11069. return Engine._ALPHA_SCREENMODE;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11075. get: function () {
  11076. return Engine._DELAYLOADSTATE_NONE;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11082. get: function () {
  11083. return Engine._DELAYLOADSTATE_LOADED;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11089. get: function () {
  11090. return Engine._DELAYLOADSTATE_LOADING;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11096. get: function () {
  11097. return Engine._DELAYLOADSTATE_NOTLOADED;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11103. get: function () {
  11104. return Engine._TEXTUREFORMAT_ALPHA;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11110. get: function () {
  11111. return Engine._TEXTUREFORMAT_LUMINANCE;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11117. /**
  11118. * R32F
  11119. */
  11120. get: function () {
  11121. return Engine._TEXTUREFORMAT_R32F;
  11122. },
  11123. enumerable: true,
  11124. configurable: true
  11125. });
  11126. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11127. /**
  11128. * RG32F
  11129. */
  11130. get: function () {
  11131. return Engine._TEXTUREFORMAT_RG32F;
  11132. },
  11133. enumerable: true,
  11134. configurable: true
  11135. });
  11136. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11137. /**
  11138. * RGB32F
  11139. */
  11140. get: function () {
  11141. return Engine._TEXTUREFORMAT_RGB32F;
  11142. },
  11143. enumerable: true,
  11144. configurable: true
  11145. });
  11146. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11147. /**
  11148. * RGBA32F
  11149. */
  11150. get: function () {
  11151. return Engine._TEXTUREFORMAT_RGBA32F;
  11152. },
  11153. enumerable: true,
  11154. configurable: true
  11155. });
  11156. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11157. get: function () {
  11158. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11159. },
  11160. enumerable: true,
  11161. configurable: true
  11162. });
  11163. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11164. get: function () {
  11165. return Engine._TEXTUREFORMAT_RGB;
  11166. },
  11167. enumerable: true,
  11168. configurable: true
  11169. });
  11170. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11171. get: function () {
  11172. return Engine._TEXTUREFORMAT_RGBA;
  11173. },
  11174. enumerable: true,
  11175. configurable: true
  11176. });
  11177. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11178. get: function () {
  11179. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11180. },
  11181. enumerable: true,
  11182. configurable: true
  11183. });
  11184. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11185. get: function () {
  11186. return Engine._TEXTURETYPE_FLOAT;
  11187. },
  11188. enumerable: true,
  11189. configurable: true
  11190. });
  11191. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11192. get: function () {
  11193. return Engine._TEXTURETYPE_HALF_FLOAT;
  11194. },
  11195. enumerable: true,
  11196. configurable: true
  11197. });
  11198. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11199. get: function () {
  11200. return Engine._SCALEMODE_FLOOR;
  11201. },
  11202. enumerable: true,
  11203. configurable: true
  11204. });
  11205. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11206. get: function () {
  11207. return Engine._SCALEMODE_NEAREST;
  11208. },
  11209. enumerable: true,
  11210. configurable: true
  11211. });
  11212. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11213. get: function () {
  11214. return Engine._SCALEMODE_CEILING;
  11215. },
  11216. enumerable: true,
  11217. configurable: true
  11218. });
  11219. Object.defineProperty(Engine, "Version", {
  11220. get: function () {
  11221. return "3.2.0-beta.2";
  11222. },
  11223. enumerable: true,
  11224. configurable: true
  11225. });
  11226. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11227. get: function () {
  11228. return this._vrExclusivePointerMode;
  11229. },
  11230. enumerable: true,
  11231. configurable: true
  11232. });
  11233. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11234. get: function () {
  11235. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11236. },
  11237. enumerable: true,
  11238. configurable: true
  11239. });
  11240. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11241. get: function () {
  11242. return this._webGLVersion < 2 || this.forcePOTTextures;
  11243. },
  11244. enumerable: true,
  11245. configurable: true
  11246. });
  11247. Object.defineProperty(Engine.prototype, "badOS", {
  11248. get: function () {
  11249. return this._badOS;
  11250. },
  11251. enumerable: true,
  11252. configurable: true
  11253. });
  11254. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11255. get: function () {
  11256. return this._badDesktopOS;
  11257. },
  11258. enumerable: true,
  11259. configurable: true
  11260. });
  11261. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11262. get: function () {
  11263. return this._performanceMonitor;
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11269. get: function () {
  11270. return this._texturesSupported;
  11271. },
  11272. enumerable: true,
  11273. configurable: true
  11274. });
  11275. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11276. get: function () {
  11277. return this._textureFormatInUse;
  11278. },
  11279. enumerable: true,
  11280. configurable: true
  11281. });
  11282. Object.defineProperty(Engine.prototype, "currentViewport", {
  11283. get: function () {
  11284. return this._cachedViewport;
  11285. },
  11286. enumerable: true,
  11287. configurable: true
  11288. });
  11289. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11290. // Empty texture
  11291. get: function () {
  11292. if (!this._emptyTexture) {
  11293. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11294. }
  11295. return this._emptyTexture;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11301. get: function () {
  11302. if (!this._emptyTexture3D) {
  11303. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11304. }
  11305. return this._emptyTexture3D;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11311. get: function () {
  11312. if (!this._emptyCubeTexture) {
  11313. var faceData = new Uint8Array(4);
  11314. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11315. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11316. }
  11317. return this._emptyCubeTexture;
  11318. },
  11319. enumerable: true,
  11320. configurable: true
  11321. });
  11322. Engine.prototype._rebuildInternalTextures = function () {
  11323. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11324. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11325. var internalTexture = currentState_1[_i];
  11326. internalTexture._rebuild();
  11327. }
  11328. };
  11329. Engine.prototype._rebuildEffects = function () {
  11330. for (var key in this._compiledEffects) {
  11331. var effect = this._compiledEffects[key];
  11332. effect._prepareEffect();
  11333. }
  11334. BABYLON.Effect.ResetCache();
  11335. };
  11336. Engine.prototype._rebuildBuffers = function () {
  11337. // Index / Vertex
  11338. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11339. var scene = _a[_i];
  11340. scene.resetCachedMaterial();
  11341. scene._rebuildGeometries();
  11342. scene._rebuildTextures();
  11343. }
  11344. // Uniforms
  11345. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11346. var uniformBuffer = _c[_b];
  11347. uniformBuffer._rebuild();
  11348. }
  11349. };
  11350. Engine.prototype._initGLContext = function () {
  11351. // Caps
  11352. this._caps = new EngineCapabilities();
  11353. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11354. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11355. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11356. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11357. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11358. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11359. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11360. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11361. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11362. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11363. // Infos
  11364. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11365. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11366. if (rendererInfo != null) {
  11367. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11368. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11369. }
  11370. if (!this._glVendor) {
  11371. this._glVendor = "Unknown vendor";
  11372. }
  11373. if (!this._glRenderer) {
  11374. this._glRenderer = "Unknown renderer";
  11375. }
  11376. // Constants
  11377. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11378. if (this._gl.RGBA16F !== 0x881A) {
  11379. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11380. }
  11381. if (this._gl.RGBA32F !== 0x8814) {
  11382. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11383. }
  11384. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11385. this._gl.DEPTH24_STENCIL8 = 35056;
  11386. }
  11387. // Extensions
  11388. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11389. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11390. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11391. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11392. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11393. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11394. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11395. 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');
  11396. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11397. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11398. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11399. this._caps.highPrecisionShaderSupported = true;
  11400. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11401. if (this._caps.timerQuery) {
  11402. if (this._webGLVersion === 1) {
  11403. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11404. }
  11405. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11406. }
  11407. // Checks if some of the format renders first to allow the use of webgl inspector.
  11408. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11409. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11410. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11411. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11412. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11413. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11414. if (this._webGLVersion > 1) {
  11415. this._gl.HALF_FLOAT_OES = 0x140B;
  11416. }
  11417. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11418. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11419. // Draw buffers
  11420. if (this._webGLVersion > 1) {
  11421. this._caps.drawBuffersExtension = true;
  11422. }
  11423. else {
  11424. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11425. if (drawBuffersExtension !== null) {
  11426. this._caps.drawBuffersExtension = true;
  11427. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11428. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11429. for (var i = 0; i < 16; i++) {
  11430. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11431. }
  11432. }
  11433. else {
  11434. this._caps.drawBuffersExtension = false;
  11435. }
  11436. }
  11437. // Depth Texture
  11438. if (this._webGLVersion > 1) {
  11439. this._caps.depthTextureExtension = true;
  11440. }
  11441. else {
  11442. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11443. if (depthTextureExtension != null) {
  11444. this._caps.depthTextureExtension = true;
  11445. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11446. }
  11447. }
  11448. // Vertex array object
  11449. if (this._webGLVersion > 1) {
  11450. this._caps.vertexArrayObject = true;
  11451. }
  11452. else {
  11453. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11454. if (vertexArrayObjectExtension != null) {
  11455. this._caps.vertexArrayObject = true;
  11456. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11457. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11458. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11459. }
  11460. else {
  11461. this._caps.vertexArrayObject = false;
  11462. }
  11463. }
  11464. // Instances count
  11465. if (this._webGLVersion > 1) {
  11466. this._caps.instancedArrays = true;
  11467. }
  11468. else {
  11469. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11470. if (instanceExtension != null) {
  11471. this._caps.instancedArrays = true;
  11472. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11473. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11474. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11475. }
  11476. else {
  11477. this._caps.instancedArrays = false;
  11478. }
  11479. }
  11480. // Intelligently add supported compressed formats in order to check for.
  11481. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11482. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11483. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11484. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11485. if (this._caps.astc)
  11486. this.texturesSupported.push('-astc.ktx');
  11487. if (this._caps.s3tc)
  11488. this.texturesSupported.push('-dxt.ktx');
  11489. if (this._caps.pvrtc)
  11490. this.texturesSupported.push('-pvrtc.ktx');
  11491. if (this._caps.etc2)
  11492. this.texturesSupported.push('-etc2.ktx');
  11493. if (this._caps.etc1)
  11494. this.texturesSupported.push('-etc1.ktx');
  11495. if (this._gl.getShaderPrecisionFormat) {
  11496. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11497. if (highp) {
  11498. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11499. }
  11500. }
  11501. // Depth buffer
  11502. this.setDepthBuffer(true);
  11503. this.setDepthFunctionToLessOrEqual();
  11504. this.setDepthWrite(true);
  11505. // Texture maps
  11506. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11507. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11508. this._nextFreeTextureSlots.push(slot);
  11509. }
  11510. };
  11511. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11512. get: function () {
  11513. return this._webGLVersion;
  11514. },
  11515. enumerable: true,
  11516. configurable: true
  11517. });
  11518. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11519. /**
  11520. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11521. */
  11522. get: function () {
  11523. return this._isStencilEnable;
  11524. },
  11525. enumerable: true,
  11526. configurable: true
  11527. });
  11528. Engine.prototype._prepareWorkingCanvas = function () {
  11529. if (this._workingCanvas) {
  11530. return;
  11531. }
  11532. this._workingCanvas = document.createElement("canvas");
  11533. var context = this._workingCanvas.getContext("2d");
  11534. if (context) {
  11535. this._workingContext = context;
  11536. }
  11537. };
  11538. Engine.prototype.resetTextureCache = function () {
  11539. for (var key in this._boundTexturesCache) {
  11540. var boundTexture = this._boundTexturesCache[key];
  11541. if (boundTexture) {
  11542. this._removeDesignatedSlot(boundTexture);
  11543. }
  11544. this._boundTexturesCache[key] = null;
  11545. }
  11546. if (!this.disableTextureBindingOptimization) {
  11547. this._nextFreeTextureSlots = [];
  11548. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11549. this._nextFreeTextureSlots.push(slot);
  11550. }
  11551. }
  11552. this._currentTextureChannel = -1;
  11553. };
  11554. Engine.prototype.isDeterministicLockStep = function () {
  11555. return this._deterministicLockstep;
  11556. };
  11557. Engine.prototype.getLockstepMaxSteps = function () {
  11558. return this._lockstepMaxSteps;
  11559. };
  11560. Engine.prototype.getGlInfo = function () {
  11561. return {
  11562. vendor: this._glVendor,
  11563. renderer: this._glRenderer,
  11564. version: this._glVersion
  11565. };
  11566. };
  11567. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11568. if (useScreen === void 0) { useScreen = false; }
  11569. var viewport = camera.viewport;
  11570. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11571. };
  11572. Engine.prototype.getRenderWidth = function (useScreen) {
  11573. if (useScreen === void 0) { useScreen = false; }
  11574. if (!useScreen && this._currentRenderTarget) {
  11575. return this._currentRenderTarget.width;
  11576. }
  11577. return this._gl.drawingBufferWidth;
  11578. };
  11579. Engine.prototype.getRenderHeight = function (useScreen) {
  11580. if (useScreen === void 0) { useScreen = false; }
  11581. if (!useScreen && this._currentRenderTarget) {
  11582. return this._currentRenderTarget.height;
  11583. }
  11584. return this._gl.drawingBufferHeight;
  11585. };
  11586. Engine.prototype.getRenderingCanvas = function () {
  11587. return this._renderingCanvas;
  11588. };
  11589. Engine.prototype.getRenderingCanvasClientRect = function () {
  11590. if (!this._renderingCanvas) {
  11591. return null;
  11592. }
  11593. return this._renderingCanvas.getBoundingClientRect();
  11594. };
  11595. Engine.prototype.setHardwareScalingLevel = function (level) {
  11596. this._hardwareScalingLevel = level;
  11597. this.resize();
  11598. };
  11599. Engine.prototype.getHardwareScalingLevel = function () {
  11600. return this._hardwareScalingLevel;
  11601. };
  11602. Engine.prototype.getLoadedTexturesCache = function () {
  11603. return this._internalTexturesCache;
  11604. };
  11605. Engine.prototype.getCaps = function () {
  11606. return this._caps;
  11607. };
  11608. Object.defineProperty(Engine.prototype, "drawCalls", {
  11609. /** The number of draw calls submitted last frame */
  11610. get: function () {
  11611. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11612. return 0;
  11613. },
  11614. enumerable: true,
  11615. configurable: true
  11616. });
  11617. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11618. get: function () {
  11619. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11620. return null;
  11621. },
  11622. enumerable: true,
  11623. configurable: true
  11624. });
  11625. Engine.prototype.getDepthFunction = function () {
  11626. return this._depthCullingState.depthFunc;
  11627. };
  11628. Engine.prototype.setDepthFunction = function (depthFunc) {
  11629. this._depthCullingState.depthFunc = depthFunc;
  11630. };
  11631. Engine.prototype.setDepthFunctionToGreater = function () {
  11632. this._depthCullingState.depthFunc = this._gl.GREATER;
  11633. };
  11634. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11635. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11636. };
  11637. Engine.prototype.setDepthFunctionToLess = function () {
  11638. this._depthCullingState.depthFunc = this._gl.LESS;
  11639. };
  11640. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11641. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11642. };
  11643. Engine.prototype.getStencilBuffer = function () {
  11644. return this._stencilState.stencilTest;
  11645. };
  11646. Engine.prototype.setStencilBuffer = function (enable) {
  11647. this._stencilState.stencilTest = enable;
  11648. };
  11649. Engine.prototype.getStencilMask = function () {
  11650. return this._stencilState.stencilMask;
  11651. };
  11652. Engine.prototype.setStencilMask = function (mask) {
  11653. this._stencilState.stencilMask = mask;
  11654. };
  11655. Engine.prototype.getStencilFunction = function () {
  11656. return this._stencilState.stencilFunc;
  11657. };
  11658. Engine.prototype.getStencilFunctionReference = function () {
  11659. return this._stencilState.stencilFuncRef;
  11660. };
  11661. Engine.prototype.getStencilFunctionMask = function () {
  11662. return this._stencilState.stencilFuncMask;
  11663. };
  11664. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11665. this._stencilState.stencilFunc = stencilFunc;
  11666. };
  11667. Engine.prototype.setStencilFunctionReference = function (reference) {
  11668. this._stencilState.stencilFuncRef = reference;
  11669. };
  11670. Engine.prototype.setStencilFunctionMask = function (mask) {
  11671. this._stencilState.stencilFuncMask = mask;
  11672. };
  11673. Engine.prototype.getStencilOperationFail = function () {
  11674. return this._stencilState.stencilOpStencilFail;
  11675. };
  11676. Engine.prototype.getStencilOperationDepthFail = function () {
  11677. return this._stencilState.stencilOpDepthFail;
  11678. };
  11679. Engine.prototype.getStencilOperationPass = function () {
  11680. return this._stencilState.stencilOpStencilDepthPass;
  11681. };
  11682. Engine.prototype.setStencilOperationFail = function (operation) {
  11683. this._stencilState.stencilOpStencilFail = operation;
  11684. };
  11685. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11686. this._stencilState.stencilOpDepthFail = operation;
  11687. };
  11688. Engine.prototype.setStencilOperationPass = function (operation) {
  11689. this._stencilState.stencilOpStencilDepthPass = operation;
  11690. };
  11691. Engine.prototype.setDitheringState = function (value) {
  11692. if (value) {
  11693. this._gl.enable(this._gl.DITHER);
  11694. }
  11695. else {
  11696. this._gl.disable(this._gl.DITHER);
  11697. }
  11698. };
  11699. Engine.prototype.setRasterizerState = function (value) {
  11700. if (value) {
  11701. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11702. }
  11703. else {
  11704. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11705. }
  11706. };
  11707. /**
  11708. * stop executing a render loop function and remove it from the execution array
  11709. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11710. */
  11711. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11712. if (!renderFunction) {
  11713. this._activeRenderLoops = [];
  11714. return;
  11715. }
  11716. var index = this._activeRenderLoops.indexOf(renderFunction);
  11717. if (index >= 0) {
  11718. this._activeRenderLoops.splice(index, 1);
  11719. }
  11720. };
  11721. Engine.prototype._renderLoop = function () {
  11722. if (!this._contextWasLost) {
  11723. var shouldRender = true;
  11724. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11725. shouldRender = false;
  11726. }
  11727. if (shouldRender) {
  11728. // Start new frame
  11729. this.beginFrame();
  11730. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11731. var renderFunction = this._activeRenderLoops[index];
  11732. renderFunction();
  11733. }
  11734. // Present
  11735. this.endFrame();
  11736. }
  11737. }
  11738. if (this._activeRenderLoops.length > 0) {
  11739. // Register new frame
  11740. var requester = null;
  11741. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11742. requester = this._vrDisplay;
  11743. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11744. }
  11745. else {
  11746. this._renderingQueueLaunched = false;
  11747. }
  11748. };
  11749. /**
  11750. * Register and execute a render loop. The engine can have more than one render function.
  11751. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11752. * @example
  11753. * engine.runRenderLoop(function () {
  11754. * scene.render()
  11755. * })
  11756. */
  11757. Engine.prototype.runRenderLoop = function (renderFunction) {
  11758. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11759. return;
  11760. }
  11761. this._activeRenderLoops.push(renderFunction);
  11762. if (!this._renderingQueueLaunched) {
  11763. this._renderingQueueLaunched = true;
  11764. this._bindedRenderFunction = this._renderLoop.bind(this);
  11765. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11766. }
  11767. };
  11768. /**
  11769. * Toggle full screen mode.
  11770. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11771. * @param {any} options - an options object to be sent to the requestFullscreen function
  11772. */
  11773. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11774. if (this.isFullscreen) {
  11775. BABYLON.Tools.ExitFullscreen();
  11776. }
  11777. else {
  11778. this._pointerLockRequested = requestPointerLock;
  11779. if (this._renderingCanvas) {
  11780. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11781. }
  11782. }
  11783. };
  11784. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11785. if (stencil === void 0) { stencil = false; }
  11786. this.applyStates();
  11787. var mode = 0;
  11788. if (backBuffer && color) {
  11789. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11790. mode |= this._gl.COLOR_BUFFER_BIT;
  11791. }
  11792. if (depth) {
  11793. this._gl.clearDepth(1.0);
  11794. mode |= this._gl.DEPTH_BUFFER_BIT;
  11795. }
  11796. if (stencil) {
  11797. this._gl.clearStencil(0);
  11798. mode |= this._gl.STENCIL_BUFFER_BIT;
  11799. }
  11800. this._gl.clear(mode);
  11801. };
  11802. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11803. var gl = this._gl;
  11804. // Save state
  11805. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11806. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11807. // Change state
  11808. gl.enable(gl.SCISSOR_TEST);
  11809. gl.scissor(x, y, width, height);
  11810. // Clear
  11811. this.clear(clearColor, true, true, true);
  11812. // Restore state
  11813. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11814. if (curScissor === true) {
  11815. gl.enable(gl.SCISSOR_TEST);
  11816. }
  11817. else {
  11818. gl.disable(gl.SCISSOR_TEST);
  11819. }
  11820. };
  11821. /**
  11822. * Set the WebGL's viewport
  11823. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11824. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11825. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11826. */
  11827. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11828. var width = requiredWidth || this.getRenderWidth();
  11829. var height = requiredHeight || this.getRenderHeight();
  11830. var x = viewport.x || 0;
  11831. var y = viewport.y || 0;
  11832. this._cachedViewport = viewport;
  11833. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11834. };
  11835. /**
  11836. * Directly set the WebGL Viewport
  11837. * The x, y, width & height are directly passed to the WebGL call
  11838. * @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.
  11839. */
  11840. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11841. var currentViewport = this._cachedViewport;
  11842. this._cachedViewport = null;
  11843. this._gl.viewport(x, y, width, height);
  11844. return currentViewport;
  11845. };
  11846. Engine.prototype.beginFrame = function () {
  11847. this.onBeginFrameObservable.notifyObservers(this);
  11848. this._measureFps();
  11849. };
  11850. Engine.prototype.endFrame = function () {
  11851. //force a flush in case we are using a bad OS.
  11852. if (this._badOS) {
  11853. this.flushFramebuffer();
  11854. }
  11855. //submit frame to the vr device, if enabled
  11856. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11857. // TODO: We should only submit the frame if we read frameData successfully.
  11858. this._vrDisplay.submitFrame();
  11859. }
  11860. this.onEndFrameObservable.notifyObservers(this);
  11861. };
  11862. /**
  11863. * resize the view according to the canvas' size.
  11864. * @example
  11865. * window.addEventListener("resize", function () {
  11866. * engine.resize();
  11867. * });
  11868. */
  11869. Engine.prototype.resize = function () {
  11870. // We're not resizing the size of the canvas while in VR mode & presenting
  11871. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11872. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11873. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11874. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11875. }
  11876. };
  11877. /**
  11878. * force a specific size of the canvas
  11879. * @param {number} width - the new canvas' width
  11880. * @param {number} height - the new canvas' height
  11881. */
  11882. Engine.prototype.setSize = function (width, height) {
  11883. if (!this._renderingCanvas) {
  11884. return;
  11885. }
  11886. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11887. return;
  11888. }
  11889. this._renderingCanvas.width = width;
  11890. this._renderingCanvas.height = height;
  11891. for (var index = 0; index < this.scenes.length; index++) {
  11892. var scene = this.scenes[index];
  11893. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11894. var cam = scene.cameras[camIndex];
  11895. cam._currentRenderId = 0;
  11896. }
  11897. }
  11898. if (this.onResizeObservable.hasObservers) {
  11899. this.onResizeObservable.notifyObservers(this);
  11900. }
  11901. };
  11902. // WebVR functions
  11903. Engine.prototype.isVRDevicePresent = function () {
  11904. return !!this._vrDisplay;
  11905. };
  11906. Engine.prototype.getVRDevice = function () {
  11907. return this._vrDisplay;
  11908. };
  11909. /**
  11910. * Initializes a webVR display and starts listening to display change events.
  11911. * The onVRDisplayChangedObservable will be notified upon these changes.
  11912. * @returns The onVRDisplayChangedObservable.
  11913. */
  11914. Engine.prototype.initWebVR = function () {
  11915. this.initWebVRAsync();
  11916. return this.onVRDisplayChangedObservable;
  11917. };
  11918. /**
  11919. * Initializes a webVR display and starts listening to display change events.
  11920. * The onVRDisplayChangedObservable will be notified upon these changes.
  11921. * @returns A promise containing a VRDisplay and if vr is supported.
  11922. */
  11923. Engine.prototype.initWebVRAsync = function () {
  11924. var _this = this;
  11925. var notifyObservers = function () {
  11926. var eventArgs = {
  11927. vrDisplay: _this._vrDisplay,
  11928. vrSupported: _this._vrSupported
  11929. };
  11930. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11931. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11932. };
  11933. if (!this._onVrDisplayConnect) {
  11934. this._onVrDisplayConnect = function (event) {
  11935. _this._vrDisplay = event.display;
  11936. notifyObservers();
  11937. };
  11938. this._onVrDisplayDisconnect = function () {
  11939. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11940. _this._vrDisplay = undefined;
  11941. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11942. notifyObservers();
  11943. };
  11944. this._onVrDisplayPresentChange = function () {
  11945. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11946. };
  11947. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11948. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11949. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11950. }
  11951. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11952. this._webVRInitPromise.then(notifyObservers);
  11953. return this._webVRInitPromise;
  11954. };
  11955. Engine.prototype.enableVR = function () {
  11956. var _this = this;
  11957. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11958. var onResolved = function () {
  11959. _this.onVRRequestPresentComplete.notifyObservers(true);
  11960. _this._onVRFullScreenTriggered();
  11961. };
  11962. var onRejected = function () {
  11963. _this.onVRRequestPresentComplete.notifyObservers(false);
  11964. };
  11965. this.onVRRequestPresentStart.notifyObservers(this);
  11966. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11967. }
  11968. };
  11969. Engine.prototype.disableVR = function () {
  11970. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11971. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11972. }
  11973. };
  11974. Engine.prototype._getVRDisplaysAsync = function () {
  11975. var _this = this;
  11976. return new Promise(function (res, rej) {
  11977. if (navigator.getVRDisplays) {
  11978. navigator.getVRDisplays().then(function (devices) {
  11979. _this._vrSupported = true;
  11980. // note that devices may actually be an empty array. This is fine;
  11981. // we expect this._vrDisplay to be undefined in this case.
  11982. _this._vrDisplay = devices[0];
  11983. res({
  11984. vrDisplay: _this._vrDisplay,
  11985. vrSupported: _this._vrSupported
  11986. });
  11987. });
  11988. }
  11989. else {
  11990. _this._vrDisplay = undefined;
  11991. _this._vrSupported = false;
  11992. res({
  11993. vrDisplay: _this._vrDisplay,
  11994. vrSupported: _this._vrSupported
  11995. });
  11996. }
  11997. });
  11998. };
  11999. /**
  12000. * Binds the frame buffer to the specified texture.
  12001. * @param texture The texture to render to or null for the default canvas
  12002. * @param faceIndex The face of the texture to render to in case of cube texture
  12003. * @param requiredWidth The width of the target to render to
  12004. * @param requiredHeight The height of the target to render to
  12005. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12006. * @param depthStencilTexture The depth stencil texture to use to render
  12007. */
  12008. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12009. if (this._currentRenderTarget) {
  12010. this.unBindFramebuffer(this._currentRenderTarget);
  12011. }
  12012. this._currentRenderTarget = texture;
  12013. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12014. var gl = this._gl;
  12015. if (texture.isCube) {
  12016. if (faceIndex === undefined) {
  12017. faceIndex = 0;
  12018. }
  12019. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12020. if (depthStencilTexture) {
  12021. if (depthStencilTexture._generateStencilBuffer) {
  12022. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12023. }
  12024. else {
  12025. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12026. }
  12027. }
  12028. }
  12029. if (this._cachedViewport && !forceFullscreenViewport) {
  12030. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12031. }
  12032. else {
  12033. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12034. }
  12035. this.wipeCaches();
  12036. };
  12037. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12038. if (this._currentFramebuffer !== framebuffer) {
  12039. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12040. this._currentFramebuffer = framebuffer;
  12041. }
  12042. };
  12043. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12044. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12045. this._currentRenderTarget = null;
  12046. // If MSAA, we need to bitblt back to main texture
  12047. var gl = this._gl;
  12048. if (texture._MSAAFramebuffer) {
  12049. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12050. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12051. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12052. }
  12053. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12054. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12055. gl.generateMipmap(gl.TEXTURE_2D);
  12056. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12057. }
  12058. if (onBeforeUnbind) {
  12059. if (texture._MSAAFramebuffer) {
  12060. // Bind the correct framebuffer
  12061. this.bindUnboundFramebuffer(texture._framebuffer);
  12062. }
  12063. onBeforeUnbind();
  12064. }
  12065. this.bindUnboundFramebuffer(null);
  12066. };
  12067. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12068. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12069. this._currentRenderTarget = null;
  12070. // If MSAA, we need to bitblt back to main texture
  12071. var gl = this._gl;
  12072. if (textures[0]._MSAAFramebuffer) {
  12073. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12074. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12075. var attachments = textures[0]._attachments;
  12076. if (!attachments) {
  12077. attachments = new Array(textures.length);
  12078. textures[0]._attachments = attachments;
  12079. }
  12080. for (var i = 0; i < textures.length; i++) {
  12081. var texture = textures[i];
  12082. for (var j = 0; j < attachments.length; j++) {
  12083. attachments[j] = gl.NONE;
  12084. }
  12085. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12086. gl.readBuffer(attachments[i]);
  12087. gl.drawBuffers(attachments);
  12088. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12089. }
  12090. for (var i = 0; i < attachments.length; i++) {
  12091. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12092. }
  12093. gl.drawBuffers(attachments);
  12094. }
  12095. for (var i = 0; i < textures.length; i++) {
  12096. var texture = textures[i];
  12097. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12098. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12099. gl.generateMipmap(gl.TEXTURE_2D);
  12100. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12101. }
  12102. }
  12103. if (onBeforeUnbind) {
  12104. if (textures[0]._MSAAFramebuffer) {
  12105. // Bind the correct framebuffer
  12106. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12107. }
  12108. onBeforeUnbind();
  12109. }
  12110. this.bindUnboundFramebuffer(null);
  12111. };
  12112. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12113. if (texture.generateMipMaps) {
  12114. var gl = this._gl;
  12115. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12116. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12117. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12118. }
  12119. };
  12120. Engine.prototype.flushFramebuffer = function () {
  12121. this._gl.flush();
  12122. };
  12123. Engine.prototype.restoreDefaultFramebuffer = function () {
  12124. if (this._currentRenderTarget) {
  12125. this.unBindFramebuffer(this._currentRenderTarget);
  12126. }
  12127. else {
  12128. this.bindUnboundFramebuffer(null);
  12129. }
  12130. if (this._cachedViewport) {
  12131. this.setViewport(this._cachedViewport);
  12132. }
  12133. this.wipeCaches();
  12134. };
  12135. // UBOs
  12136. Engine.prototype.createUniformBuffer = function (elements) {
  12137. var ubo = this._gl.createBuffer();
  12138. if (!ubo) {
  12139. throw new Error("Unable to create uniform buffer");
  12140. }
  12141. this.bindUniformBuffer(ubo);
  12142. if (elements instanceof Float32Array) {
  12143. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12144. }
  12145. else {
  12146. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12147. }
  12148. this.bindUniformBuffer(null);
  12149. ubo.references = 1;
  12150. return ubo;
  12151. };
  12152. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12153. var ubo = this._gl.createBuffer();
  12154. if (!ubo) {
  12155. throw new Error("Unable to create dynamic uniform buffer");
  12156. }
  12157. this.bindUniformBuffer(ubo);
  12158. if (elements instanceof Float32Array) {
  12159. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12160. }
  12161. else {
  12162. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12163. }
  12164. this.bindUniformBuffer(null);
  12165. ubo.references = 1;
  12166. return ubo;
  12167. };
  12168. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12169. this.bindUniformBuffer(uniformBuffer);
  12170. if (offset === undefined) {
  12171. offset = 0;
  12172. }
  12173. if (count === undefined) {
  12174. if (elements instanceof Float32Array) {
  12175. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12176. }
  12177. else {
  12178. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12179. }
  12180. }
  12181. else {
  12182. if (elements instanceof Float32Array) {
  12183. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12184. }
  12185. else {
  12186. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12187. }
  12188. }
  12189. this.bindUniformBuffer(null);
  12190. };
  12191. // VBOs
  12192. Engine.prototype._resetVertexBufferBinding = function () {
  12193. this.bindArrayBuffer(null);
  12194. this._cachedVertexBuffers = null;
  12195. };
  12196. Engine.prototype.createVertexBuffer = function (vertices) {
  12197. var vbo = this._gl.createBuffer();
  12198. if (!vbo) {
  12199. throw new Error("Unable to create vertex buffer");
  12200. }
  12201. this.bindArrayBuffer(vbo);
  12202. if (vertices instanceof Float32Array) {
  12203. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12204. }
  12205. else {
  12206. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12207. }
  12208. this._resetVertexBufferBinding();
  12209. vbo.references = 1;
  12210. return vbo;
  12211. };
  12212. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12213. var vbo = this._gl.createBuffer();
  12214. if (!vbo) {
  12215. throw new Error("Unable to create dynamic vertex buffer");
  12216. }
  12217. this.bindArrayBuffer(vbo);
  12218. if (vertices instanceof Float32Array) {
  12219. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12220. }
  12221. else {
  12222. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12223. }
  12224. this._resetVertexBufferBinding();
  12225. vbo.references = 1;
  12226. return vbo;
  12227. };
  12228. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12229. if (offset === void 0) { offset = 0; }
  12230. // Force cache update
  12231. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12232. this.bindIndexBuffer(indexBuffer);
  12233. var arrayBuffer;
  12234. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12235. arrayBuffer = indices;
  12236. }
  12237. else {
  12238. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12239. }
  12240. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12241. this._resetIndexBufferBinding();
  12242. };
  12243. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12244. this.bindArrayBuffer(vertexBuffer);
  12245. if (offset === undefined) {
  12246. offset = 0;
  12247. }
  12248. if (count === undefined) {
  12249. if (vertices instanceof Float32Array) {
  12250. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12251. }
  12252. else {
  12253. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12254. }
  12255. }
  12256. else {
  12257. if (vertices instanceof Float32Array) {
  12258. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12259. }
  12260. else {
  12261. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12262. }
  12263. }
  12264. this._resetVertexBufferBinding();
  12265. };
  12266. Engine.prototype._resetIndexBufferBinding = function () {
  12267. this.bindIndexBuffer(null);
  12268. this._cachedIndexBuffer = null;
  12269. };
  12270. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12271. var vbo = this._gl.createBuffer();
  12272. if (!vbo) {
  12273. throw new Error("Unable to create index buffer");
  12274. }
  12275. this.bindIndexBuffer(vbo);
  12276. // Check for 32 bits indices
  12277. var arrayBuffer;
  12278. var need32Bits = false;
  12279. if (indices instanceof Uint16Array) {
  12280. arrayBuffer = indices;
  12281. }
  12282. else {
  12283. //check 32 bit support
  12284. if (this._caps.uintIndices) {
  12285. if (indices instanceof Uint32Array) {
  12286. arrayBuffer = indices;
  12287. need32Bits = true;
  12288. }
  12289. else {
  12290. //number[] or Int32Array, check if 32 bit is necessary
  12291. for (var index = 0; index < indices.length; index++) {
  12292. if (indices[index] > 65535) {
  12293. need32Bits = true;
  12294. break;
  12295. }
  12296. }
  12297. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12298. }
  12299. }
  12300. else {
  12301. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12302. arrayBuffer = new Uint16Array(indices);
  12303. }
  12304. }
  12305. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12306. this._resetIndexBufferBinding();
  12307. vbo.references = 1;
  12308. vbo.is32Bits = need32Bits;
  12309. return vbo;
  12310. };
  12311. Engine.prototype.bindArrayBuffer = function (buffer) {
  12312. if (!this._vaoRecordInProgress) {
  12313. this._unbindVertexArrayObject();
  12314. }
  12315. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12316. };
  12317. Engine.prototype.bindUniformBuffer = function (buffer) {
  12318. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12319. };
  12320. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12321. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12322. };
  12323. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12324. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12325. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12326. };
  12327. ;
  12328. Engine.prototype.bindIndexBuffer = function (buffer) {
  12329. if (!this._vaoRecordInProgress) {
  12330. this._unbindVertexArrayObject();
  12331. }
  12332. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12333. };
  12334. Engine.prototype.bindBuffer = function (buffer, target) {
  12335. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12336. this._gl.bindBuffer(target, buffer);
  12337. this._currentBoundBuffer[target] = buffer;
  12338. }
  12339. };
  12340. Engine.prototype.updateArrayBuffer = function (data) {
  12341. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12342. };
  12343. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12344. var pointer = this._currentBufferPointers[indx];
  12345. var changed = false;
  12346. if (!pointer.active) {
  12347. changed = true;
  12348. pointer.active = true;
  12349. pointer.index = indx;
  12350. pointer.size = size;
  12351. pointer.type = type;
  12352. pointer.normalized = normalized;
  12353. pointer.stride = stride;
  12354. pointer.offset = offset;
  12355. pointer.buffer = buffer;
  12356. }
  12357. else {
  12358. if (pointer.buffer !== buffer) {
  12359. pointer.buffer = buffer;
  12360. changed = true;
  12361. }
  12362. if (pointer.size !== size) {
  12363. pointer.size = size;
  12364. changed = true;
  12365. }
  12366. if (pointer.type !== type) {
  12367. pointer.type = type;
  12368. changed = true;
  12369. }
  12370. if (pointer.normalized !== normalized) {
  12371. pointer.normalized = normalized;
  12372. changed = true;
  12373. }
  12374. if (pointer.stride !== stride) {
  12375. pointer.stride = stride;
  12376. changed = true;
  12377. }
  12378. if (pointer.offset !== offset) {
  12379. pointer.offset = offset;
  12380. changed = true;
  12381. }
  12382. }
  12383. if (changed || this._vaoRecordInProgress) {
  12384. this.bindArrayBuffer(buffer);
  12385. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12386. }
  12387. };
  12388. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12389. if (indexBuffer == null) {
  12390. return;
  12391. }
  12392. if (this._cachedIndexBuffer !== indexBuffer) {
  12393. this._cachedIndexBuffer = indexBuffer;
  12394. this.bindIndexBuffer(indexBuffer);
  12395. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12396. }
  12397. };
  12398. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12399. var attributes = effect.getAttributesNames();
  12400. if (!this._vaoRecordInProgress) {
  12401. this._unbindVertexArrayObject();
  12402. }
  12403. this.unbindAllAttributes();
  12404. for (var index = 0; index < attributes.length; index++) {
  12405. var order = effect.getAttributeLocation(index);
  12406. if (order >= 0) {
  12407. var vertexBuffer = vertexBuffers[attributes[index]];
  12408. if (!vertexBuffer) {
  12409. continue;
  12410. }
  12411. this._gl.enableVertexAttribArray(order);
  12412. if (!this._vaoRecordInProgress) {
  12413. this._vertexAttribArraysEnabled[order] = true;
  12414. }
  12415. var buffer = vertexBuffer.getBuffer();
  12416. if (buffer) {
  12417. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12418. if (vertexBuffer.getIsInstanced()) {
  12419. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12420. if (!this._vaoRecordInProgress) {
  12421. this._currentInstanceLocations.push(order);
  12422. this._currentInstanceBuffers.push(buffer);
  12423. }
  12424. }
  12425. }
  12426. }
  12427. }
  12428. };
  12429. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12430. var vao = this._gl.createVertexArray();
  12431. this._vaoRecordInProgress = true;
  12432. this._gl.bindVertexArray(vao);
  12433. this._mustWipeVertexAttributes = true;
  12434. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12435. this.bindIndexBuffer(indexBuffer);
  12436. this._vaoRecordInProgress = false;
  12437. this._gl.bindVertexArray(null);
  12438. return vao;
  12439. };
  12440. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12441. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12442. this._cachedVertexArrayObject = vertexArrayObject;
  12443. this._gl.bindVertexArray(vertexArrayObject);
  12444. this._cachedVertexBuffers = null;
  12445. this._cachedIndexBuffer = null;
  12446. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12447. this._mustWipeVertexAttributes = true;
  12448. }
  12449. };
  12450. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12451. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12452. this._cachedVertexBuffers = vertexBuffer;
  12453. this._cachedEffectForVertexBuffers = effect;
  12454. var attributesCount = effect.getAttributesCount();
  12455. this._unbindVertexArrayObject();
  12456. this.unbindAllAttributes();
  12457. var offset = 0;
  12458. for (var index = 0; index < attributesCount; index++) {
  12459. if (index < vertexDeclaration.length) {
  12460. var order = effect.getAttributeLocation(index);
  12461. if (order >= 0) {
  12462. this._gl.enableVertexAttribArray(order);
  12463. this._vertexAttribArraysEnabled[order] = true;
  12464. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12465. }
  12466. offset += vertexDeclaration[index] * 4;
  12467. }
  12468. }
  12469. }
  12470. this._bindIndexBufferWithCache(indexBuffer);
  12471. };
  12472. Engine.prototype._unbindVertexArrayObject = function () {
  12473. if (!this._cachedVertexArrayObject) {
  12474. return;
  12475. }
  12476. this._cachedVertexArrayObject = null;
  12477. this._gl.bindVertexArray(null);
  12478. };
  12479. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12480. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12481. this._cachedVertexBuffers = vertexBuffers;
  12482. this._cachedEffectForVertexBuffers = effect;
  12483. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12484. }
  12485. this._bindIndexBufferWithCache(indexBuffer);
  12486. };
  12487. Engine.prototype.unbindInstanceAttributes = function () {
  12488. var boundBuffer;
  12489. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12490. var instancesBuffer = this._currentInstanceBuffers[i];
  12491. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12492. boundBuffer = instancesBuffer;
  12493. this.bindArrayBuffer(instancesBuffer);
  12494. }
  12495. var offsetLocation = this._currentInstanceLocations[i];
  12496. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12497. }
  12498. this._currentInstanceBuffers.length = 0;
  12499. this._currentInstanceLocations.length = 0;
  12500. };
  12501. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12502. this._gl.deleteVertexArray(vao);
  12503. };
  12504. Engine.prototype._releaseBuffer = function (buffer) {
  12505. buffer.references--;
  12506. if (buffer.references === 0) {
  12507. this._gl.deleteBuffer(buffer);
  12508. return true;
  12509. }
  12510. return false;
  12511. };
  12512. Engine.prototype.createInstancesBuffer = function (capacity) {
  12513. var buffer = this._gl.createBuffer();
  12514. if (!buffer) {
  12515. throw new Error("Unable to create instance buffer");
  12516. }
  12517. buffer.capacity = capacity;
  12518. this.bindArrayBuffer(buffer);
  12519. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12520. return buffer;
  12521. };
  12522. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12523. this._gl.deleteBuffer(buffer);
  12524. };
  12525. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12526. this.bindArrayBuffer(instancesBuffer);
  12527. if (data) {
  12528. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12529. }
  12530. if (offsetLocations[0].index !== undefined) {
  12531. var stride = 0;
  12532. for (var i = 0; i < offsetLocations.length; i++) {
  12533. var ai = offsetLocations[i];
  12534. stride += ai.attributeSize * 4;
  12535. }
  12536. for (var i = 0; i < offsetLocations.length; i++) {
  12537. var ai = offsetLocations[i];
  12538. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12539. this._gl.enableVertexAttribArray(ai.index);
  12540. this._vertexAttribArraysEnabled[ai.index] = true;
  12541. }
  12542. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12543. this._gl.vertexAttribDivisor(ai.index, 1);
  12544. this._currentInstanceLocations.push(ai.index);
  12545. this._currentInstanceBuffers.push(instancesBuffer);
  12546. }
  12547. }
  12548. else {
  12549. for (var index = 0; index < 4; index++) {
  12550. var offsetLocation = offsetLocations[index];
  12551. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12552. this._gl.enableVertexAttribArray(offsetLocation);
  12553. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12554. }
  12555. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12556. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12557. this._currentInstanceLocations.push(offsetLocation);
  12558. this._currentInstanceBuffers.push(instancesBuffer);
  12559. }
  12560. }
  12561. };
  12562. Engine.prototype.applyStates = function () {
  12563. this._depthCullingState.apply(this._gl);
  12564. this._stencilState.apply(this._gl);
  12565. this._alphaState.apply(this._gl);
  12566. };
  12567. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12568. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12569. };
  12570. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12571. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12572. };
  12573. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12574. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12575. };
  12576. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12577. // Apply states
  12578. this.applyStates();
  12579. this._drawCalls.addCount(1, false);
  12580. // Render
  12581. var drawMode = this._drawMode(fillMode);
  12582. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12583. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12584. if (instancesCount) {
  12585. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12586. }
  12587. else {
  12588. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12589. }
  12590. };
  12591. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12592. // Apply states
  12593. this.applyStates();
  12594. this._drawCalls.addCount(1, false);
  12595. var drawMode = this._drawMode(fillMode);
  12596. if (instancesCount) {
  12597. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12598. }
  12599. else {
  12600. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12601. }
  12602. };
  12603. Engine.prototype._drawMode = function (fillMode) {
  12604. switch (fillMode) {
  12605. // Triangle views
  12606. case BABYLON.Material.TriangleFillMode:
  12607. return this._gl.TRIANGLES;
  12608. case BABYLON.Material.PointFillMode:
  12609. return this._gl.POINTS;
  12610. case BABYLON.Material.WireFrameFillMode:
  12611. return this._gl.LINES;
  12612. // Draw modes
  12613. case BABYLON.Material.PointListDrawMode:
  12614. return this._gl.POINTS;
  12615. case BABYLON.Material.LineListDrawMode:
  12616. return this._gl.LINES;
  12617. case BABYLON.Material.LineLoopDrawMode:
  12618. return this._gl.LINE_LOOP;
  12619. case BABYLON.Material.LineStripDrawMode:
  12620. return this._gl.LINE_STRIP;
  12621. case BABYLON.Material.TriangleStripDrawMode:
  12622. return this._gl.TRIANGLE_STRIP;
  12623. case BABYLON.Material.TriangleFanDrawMode:
  12624. return this._gl.TRIANGLE_FAN;
  12625. default:
  12626. return this._gl.TRIANGLES;
  12627. }
  12628. };
  12629. // Shaders
  12630. Engine.prototype._releaseEffect = function (effect) {
  12631. if (this._compiledEffects[effect._key]) {
  12632. delete this._compiledEffects[effect._key];
  12633. this._deleteProgram(effect.getProgram());
  12634. }
  12635. };
  12636. Engine.prototype._deleteProgram = function (program) {
  12637. if (program) {
  12638. program.__SPECTOR_rebuildProgram = null;
  12639. if (program.transformFeedback) {
  12640. this.deleteTransformFeedback(program.transformFeedback);
  12641. program.transformFeedback = null;
  12642. }
  12643. this._gl.deleteProgram(program);
  12644. }
  12645. };
  12646. /**
  12647. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12648. * @param samplers An array of string used to represent textures
  12649. */
  12650. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12651. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12652. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12653. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12654. if (this._compiledEffects[name]) {
  12655. var compiledEffect = this._compiledEffects[name];
  12656. if (onCompiled && compiledEffect.isReady()) {
  12657. onCompiled(compiledEffect);
  12658. }
  12659. return compiledEffect;
  12660. }
  12661. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12662. effect._key = name;
  12663. this._compiledEffects[name] = effect;
  12664. return effect;
  12665. };
  12666. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12667. if (uniformsNames === void 0) { uniformsNames = []; }
  12668. if (samplers === void 0) { samplers = []; }
  12669. if (defines === void 0) { defines = ""; }
  12670. return this.createEffect({
  12671. vertex: "particles",
  12672. fragmentElement: fragmentName
  12673. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12674. };
  12675. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12676. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12677. context = context || this._gl;
  12678. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12679. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12680. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12681. };
  12682. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12683. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12684. context = context || this._gl;
  12685. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12686. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12687. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12688. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12689. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12690. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12691. return program;
  12692. };
  12693. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12694. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12695. var shaderProgram = context.createProgram();
  12696. if (!shaderProgram) {
  12697. throw new Error("Unable to create program");
  12698. }
  12699. context.attachShader(shaderProgram, vertexShader);
  12700. context.attachShader(shaderProgram, fragmentShader);
  12701. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12702. var transformFeedback = this.createTransformFeedback();
  12703. this.bindTransformFeedback(transformFeedback);
  12704. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12705. shaderProgram.transformFeedback = transformFeedback;
  12706. }
  12707. context.linkProgram(shaderProgram);
  12708. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12709. this.bindTransformFeedback(null);
  12710. }
  12711. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12712. if (!linked) {
  12713. context.validateProgram(shaderProgram);
  12714. var error = context.getProgramInfoLog(shaderProgram);
  12715. if (error) {
  12716. throw new Error(error);
  12717. }
  12718. }
  12719. context.deleteShader(vertexShader);
  12720. context.deleteShader(fragmentShader);
  12721. return shaderProgram;
  12722. };
  12723. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12724. var results = new Array();
  12725. for (var index = 0; index < uniformsNames.length; index++) {
  12726. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12727. }
  12728. return results;
  12729. };
  12730. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12731. var results = [];
  12732. for (var index = 0; index < attributesNames.length; index++) {
  12733. try {
  12734. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12735. }
  12736. catch (e) {
  12737. results.push(-1);
  12738. }
  12739. }
  12740. return results;
  12741. };
  12742. Engine.prototype.enableEffect = function (effect) {
  12743. if (!effect) {
  12744. return;
  12745. }
  12746. // Use program
  12747. this.bindSamplers(effect);
  12748. this._currentEffect = effect;
  12749. if (effect.onBind) {
  12750. effect.onBind(effect);
  12751. }
  12752. effect.onBindObservable.notifyObservers(effect);
  12753. };
  12754. Engine.prototype.setIntArray = function (uniform, array) {
  12755. if (!uniform)
  12756. return;
  12757. this._gl.uniform1iv(uniform, array);
  12758. };
  12759. Engine.prototype.setIntArray2 = function (uniform, array) {
  12760. if (!uniform || array.length % 2 !== 0)
  12761. return;
  12762. this._gl.uniform2iv(uniform, array);
  12763. };
  12764. Engine.prototype.setIntArray3 = function (uniform, array) {
  12765. if (!uniform || array.length % 3 !== 0)
  12766. return;
  12767. this._gl.uniform3iv(uniform, array);
  12768. };
  12769. Engine.prototype.setIntArray4 = function (uniform, array) {
  12770. if (!uniform || array.length % 4 !== 0)
  12771. return;
  12772. this._gl.uniform4iv(uniform, array);
  12773. };
  12774. Engine.prototype.setFloatArray = function (uniform, array) {
  12775. if (!uniform)
  12776. return;
  12777. this._gl.uniform1fv(uniform, array);
  12778. };
  12779. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12780. if (!uniform || array.length % 2 !== 0)
  12781. return;
  12782. this._gl.uniform2fv(uniform, array);
  12783. };
  12784. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12785. if (!uniform || array.length % 3 !== 0)
  12786. return;
  12787. this._gl.uniform3fv(uniform, array);
  12788. };
  12789. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12790. if (!uniform || array.length % 4 !== 0)
  12791. return;
  12792. this._gl.uniform4fv(uniform, array);
  12793. };
  12794. Engine.prototype.setArray = function (uniform, array) {
  12795. if (!uniform)
  12796. return;
  12797. this._gl.uniform1fv(uniform, array);
  12798. };
  12799. Engine.prototype.setArray2 = function (uniform, array) {
  12800. if (!uniform || array.length % 2 !== 0)
  12801. return;
  12802. this._gl.uniform2fv(uniform, array);
  12803. };
  12804. Engine.prototype.setArray3 = function (uniform, array) {
  12805. if (!uniform || array.length % 3 !== 0)
  12806. return;
  12807. this._gl.uniform3fv(uniform, array);
  12808. };
  12809. Engine.prototype.setArray4 = function (uniform, array) {
  12810. if (!uniform || array.length % 4 !== 0)
  12811. return;
  12812. this._gl.uniform4fv(uniform, array);
  12813. };
  12814. Engine.prototype.setMatrices = function (uniform, matrices) {
  12815. if (!uniform)
  12816. return;
  12817. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12818. };
  12819. Engine.prototype.setMatrix = function (uniform, matrix) {
  12820. if (!uniform)
  12821. return;
  12822. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12823. };
  12824. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12825. if (!uniform)
  12826. return;
  12827. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12828. };
  12829. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12830. if (!uniform)
  12831. return;
  12832. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12833. };
  12834. Engine.prototype.setInt = function (uniform, value) {
  12835. if (!uniform)
  12836. return;
  12837. this._gl.uniform1i(uniform, value);
  12838. };
  12839. Engine.prototype.setFloat = function (uniform, value) {
  12840. if (!uniform)
  12841. return;
  12842. this._gl.uniform1f(uniform, value);
  12843. };
  12844. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12845. if (!uniform)
  12846. return;
  12847. this._gl.uniform2f(uniform, x, y);
  12848. };
  12849. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12850. if (!uniform)
  12851. return;
  12852. this._gl.uniform3f(uniform, x, y, z);
  12853. };
  12854. Engine.prototype.setBool = function (uniform, bool) {
  12855. if (!uniform)
  12856. return;
  12857. this._gl.uniform1i(uniform, bool);
  12858. };
  12859. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12860. if (!uniform)
  12861. return;
  12862. this._gl.uniform4f(uniform, x, y, z, w);
  12863. };
  12864. Engine.prototype.setColor3 = function (uniform, color3) {
  12865. if (!uniform)
  12866. return;
  12867. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12868. };
  12869. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12870. if (!uniform)
  12871. return;
  12872. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12873. };
  12874. /**
  12875. * Sets a Color4 on a uniform variable
  12876. * @param uniform defines the uniform location
  12877. * @param color4 defines the value to be set
  12878. */
  12879. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12880. if (!uniform)
  12881. return;
  12882. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12883. };
  12884. // States
  12885. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12886. if (zOffset === void 0) { zOffset = 0; }
  12887. if (reverseSide === void 0) { reverseSide = false; }
  12888. // Culling
  12889. if (this._depthCullingState.cull !== culling || force) {
  12890. this._depthCullingState.cull = culling;
  12891. }
  12892. // Cull face
  12893. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12894. if (this._depthCullingState.cullFace !== cullFace || force) {
  12895. this._depthCullingState.cullFace = cullFace;
  12896. }
  12897. // Z offset
  12898. this.setZOffset(zOffset);
  12899. // Front face
  12900. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12901. if (this._depthCullingState.frontFace !== frontFace || force) {
  12902. this._depthCullingState.frontFace = frontFace;
  12903. }
  12904. };
  12905. Engine.prototype.setZOffset = function (value) {
  12906. this._depthCullingState.zOffset = value;
  12907. };
  12908. Engine.prototype.getZOffset = function () {
  12909. return this._depthCullingState.zOffset;
  12910. };
  12911. Engine.prototype.setDepthBuffer = function (enable) {
  12912. this._depthCullingState.depthTest = enable;
  12913. };
  12914. Engine.prototype.getDepthWrite = function () {
  12915. return this._depthCullingState.depthMask;
  12916. };
  12917. Engine.prototype.setDepthWrite = function (enable) {
  12918. this._depthCullingState.depthMask = enable;
  12919. };
  12920. Engine.prototype.setColorWrite = function (enable) {
  12921. this._gl.colorMask(enable, enable, enable, enable);
  12922. this._colorWrite = enable;
  12923. };
  12924. Engine.prototype.getColorWrite = function () {
  12925. return this._colorWrite;
  12926. };
  12927. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12928. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12929. };
  12930. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12931. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12932. if (this._alphaMode === mode) {
  12933. return;
  12934. }
  12935. switch (mode) {
  12936. case Engine.ALPHA_DISABLE:
  12937. this._alphaState.alphaBlend = false;
  12938. break;
  12939. case Engine.ALPHA_PREMULTIPLIED:
  12940. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12941. this._alphaState.alphaBlend = true;
  12942. break;
  12943. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12944. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12945. this._alphaState.alphaBlend = true;
  12946. break;
  12947. case Engine.ALPHA_COMBINE:
  12948. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12949. this._alphaState.alphaBlend = true;
  12950. break;
  12951. case Engine.ALPHA_ONEONE:
  12952. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12953. this._alphaState.alphaBlend = true;
  12954. break;
  12955. case Engine.ALPHA_ADD:
  12956. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12957. this._alphaState.alphaBlend = true;
  12958. break;
  12959. case Engine.ALPHA_SUBTRACT:
  12960. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12961. this._alphaState.alphaBlend = true;
  12962. break;
  12963. case Engine.ALPHA_MULTIPLY:
  12964. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12965. this._alphaState.alphaBlend = true;
  12966. break;
  12967. case Engine.ALPHA_MAXIMIZED:
  12968. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12969. this._alphaState.alphaBlend = true;
  12970. break;
  12971. case Engine.ALPHA_INTERPOLATE:
  12972. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12973. this._alphaState.alphaBlend = true;
  12974. break;
  12975. case Engine.ALPHA_SCREENMODE:
  12976. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12977. this._alphaState.alphaBlend = true;
  12978. break;
  12979. }
  12980. if (!noDepthWriteChange) {
  12981. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12982. }
  12983. this._alphaMode = mode;
  12984. };
  12985. Engine.prototype.getAlphaMode = function () {
  12986. return this._alphaMode;
  12987. };
  12988. // Textures
  12989. Engine.prototype.wipeCaches = function (bruteForce) {
  12990. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12991. return;
  12992. }
  12993. this._currentEffect = null;
  12994. // 6/8/2017: deltakosh: Should not be required anymore.
  12995. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12996. if (bruteForce) {
  12997. this.resetTextureCache();
  12998. this._currentProgram = null;
  12999. this._stencilState.reset();
  13000. this._depthCullingState.reset();
  13001. this.setDepthFunctionToLessOrEqual();
  13002. this._alphaState.reset();
  13003. }
  13004. this._resetVertexBufferBinding();
  13005. this._cachedIndexBuffer = null;
  13006. this._cachedEffectForVertexBuffers = null;
  13007. this._unbindVertexArrayObject();
  13008. this.bindIndexBuffer(null);
  13009. };
  13010. /**
  13011. * Set the compressed texture format to use, based on the formats you have, and the formats
  13012. * supported by the hardware / browser.
  13013. *
  13014. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13015. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13016. * to API arguments needed to compressed textures. This puts the burden on the container
  13017. * generator to house the arcane code for determining these for current & future formats.
  13018. *
  13019. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13020. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13021. *
  13022. * Note: The result of this call is not taken into account when a texture is base64.
  13023. *
  13024. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13025. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13026. *
  13027. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13028. * @returns The extension selected.
  13029. */
  13030. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13031. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13032. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13033. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13034. return this._textureFormatInUse = this._texturesSupported[i];
  13035. }
  13036. }
  13037. }
  13038. // actively set format to nothing, to allow this to be called more than once
  13039. // and possibly fail the 2nd time
  13040. this._textureFormatInUse = null;
  13041. return null;
  13042. };
  13043. Engine.prototype._createTexture = function () {
  13044. var texture = this._gl.createTexture();
  13045. if (!texture) {
  13046. throw new Error("Unable to create texture");
  13047. }
  13048. return texture;
  13049. };
  13050. /**
  13051. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13052. * @param {string} urlArg- This contains one of the following:
  13053. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13054. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13055. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13056. *
  13057. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13058. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13059. * @param {Scene} scene- Needed for loading to the correct scene.
  13060. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13061. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13062. * @param {callback} onError- Optional callback to be called upon failure.
  13063. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13064. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13065. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13066. *
  13067. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13068. */
  13069. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13070. var _this = this;
  13071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13072. if (onLoad === void 0) { onLoad = null; }
  13073. if (onError === void 0) { onError = null; }
  13074. if (buffer === void 0) { buffer = null; }
  13075. if (fallBack === void 0) { fallBack = null; }
  13076. if (format === void 0) { format = null; }
  13077. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13078. var fromData = url.substr(0, 5) === "data:";
  13079. var fromBlob = url.substr(0, 5) === "blob:";
  13080. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13081. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13082. // establish the file extension, if possible
  13083. var lastDot = url.lastIndexOf('.');
  13084. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13085. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13086. var isTGA = (extension.indexOf(".tga") === 0);
  13087. // determine if a ktx file should be substituted
  13088. var isKTX = false;
  13089. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13090. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13091. isKTX = true;
  13092. }
  13093. if (scene) {
  13094. scene._addPendingData(texture);
  13095. }
  13096. texture.url = url;
  13097. texture.generateMipMaps = !noMipmap;
  13098. texture.samplingMode = samplingMode;
  13099. texture.invertY = invertY;
  13100. if (!this._doNotHandleContextLost) {
  13101. // Keep a link to the buffer only if we plan to handle context lost
  13102. texture._buffer = buffer;
  13103. }
  13104. var onLoadObserver = null;
  13105. if (onLoad && !fallBack) {
  13106. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13107. }
  13108. if (!fallBack)
  13109. this._internalTexturesCache.push(texture);
  13110. var onerror = function (message, exception) {
  13111. if (scene) {
  13112. scene._removePendingData(texture);
  13113. }
  13114. if (onLoadObserver) {
  13115. texture.onLoadedObservable.remove(onLoadObserver);
  13116. }
  13117. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13118. if (isKTX) {
  13119. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13120. }
  13121. else if (BABYLON.Tools.UseFallbackTexture) {
  13122. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13123. }
  13124. if (onError) {
  13125. onError(message || "Unknown error", exception);
  13126. }
  13127. };
  13128. var callback = null;
  13129. // processing for non-image formats
  13130. if (isKTX || isTGA || isDDS) {
  13131. if (isKTX) {
  13132. callback = function (data) {
  13133. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13134. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13135. ktx.uploadLevels(_this._gl, !noMipmap);
  13136. return false;
  13137. }, samplingMode);
  13138. };
  13139. }
  13140. else if (isTGA) {
  13141. callback = function (arrayBuffer) {
  13142. var data = new Uint8Array(arrayBuffer);
  13143. var header = BABYLON.TGATools.GetTGAHeader(data);
  13144. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13145. BABYLON.TGATools.UploadContent(_this._gl, data);
  13146. return false;
  13147. }, samplingMode);
  13148. };
  13149. }
  13150. else if (isDDS) {
  13151. callback = function (data) {
  13152. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13153. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13154. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13155. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13156. return false;
  13157. }, samplingMode);
  13158. };
  13159. }
  13160. if (!buffer) {
  13161. this._loadFile(url, function (data) {
  13162. if (callback) {
  13163. callback(data);
  13164. }
  13165. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13166. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13167. });
  13168. }
  13169. else {
  13170. if (callback) {
  13171. callback(buffer);
  13172. }
  13173. }
  13174. // image format processing
  13175. }
  13176. else {
  13177. var onload = function (img) {
  13178. if (fromBlob && !_this._doNotHandleContextLost) {
  13179. // We need to store the image if we need to rebuild the texture
  13180. // in case of a webgl context lost
  13181. texture._buffer = img;
  13182. }
  13183. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13184. var gl = _this._gl;
  13185. var isPot = (img.width === potWidth && img.height === potHeight);
  13186. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13187. if (isPot) {
  13188. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13189. return false;
  13190. }
  13191. // Using shaders to rescale because canvas.drawImage is lossy
  13192. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13193. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13194. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13196. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13197. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13199. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13200. _this._releaseTexture(source);
  13201. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13202. continuationCallback();
  13203. });
  13204. return true;
  13205. }, samplingMode);
  13206. };
  13207. if (!fromData || isBase64)
  13208. if (buffer instanceof HTMLImageElement) {
  13209. onload(buffer);
  13210. }
  13211. else {
  13212. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13213. }
  13214. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13215. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13216. else
  13217. onload(buffer);
  13218. }
  13219. return texture;
  13220. };
  13221. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13222. var _this = this;
  13223. var rtt = this.createRenderTargetTexture({
  13224. width: destination.width,
  13225. height: destination.height,
  13226. }, {
  13227. generateMipMaps: false,
  13228. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13229. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13230. generateDepthBuffer: false,
  13231. generateStencilBuffer: false
  13232. });
  13233. if (!this._rescalePostProcess) {
  13234. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13235. }
  13236. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13237. _this._rescalePostProcess.onApply = function (effect) {
  13238. effect._bindTexture("textureSampler", source);
  13239. };
  13240. var hostingScene = scene;
  13241. if (!hostingScene) {
  13242. hostingScene = _this.scenes[_this.scenes.length - 1];
  13243. }
  13244. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13245. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13246. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13247. _this.unBindFramebuffer(rtt);
  13248. _this._releaseTexture(rtt);
  13249. if (onComplete) {
  13250. onComplete();
  13251. }
  13252. });
  13253. };
  13254. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13255. if (compression === void 0) { compression = null; }
  13256. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13257. if (!texture) {
  13258. return;
  13259. }
  13260. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13261. var internalFormat = this._getInternalFormat(format);
  13262. var textureType = this._getWebGLTextureType(type);
  13263. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13264. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13265. if (!this._doNotHandleContextLost) {
  13266. texture._bufferView = data;
  13267. texture.format = format;
  13268. texture.type = type;
  13269. texture.invertY = invertY;
  13270. texture._compression = compression;
  13271. }
  13272. if (texture.width % 4 !== 0) {
  13273. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13274. }
  13275. if (compression && data) {
  13276. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13277. }
  13278. else {
  13279. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13280. }
  13281. if (texture.generateMipMaps) {
  13282. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13283. }
  13284. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13285. // this.resetTextureCache();
  13286. texture.isReady = true;
  13287. };
  13288. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13289. if (compression === void 0) { compression = null; }
  13290. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13291. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13292. texture.baseWidth = width;
  13293. texture.baseHeight = height;
  13294. texture.width = width;
  13295. texture.height = height;
  13296. texture.format = format;
  13297. texture.generateMipMaps = generateMipMaps;
  13298. texture.samplingMode = samplingMode;
  13299. texture.invertY = invertY;
  13300. texture._compression = compression;
  13301. texture.type = type;
  13302. if (!this._doNotHandleContextLost) {
  13303. texture._bufferView = data;
  13304. }
  13305. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13306. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13307. // Filters
  13308. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13309. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13310. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13311. if (generateMipMaps) {
  13312. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13313. }
  13314. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13315. this._internalTexturesCache.push(texture);
  13316. return texture;
  13317. };
  13318. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13319. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13320. texture.baseWidth = width;
  13321. texture.baseHeight = height;
  13322. if (generateMipMaps) {
  13323. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13324. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13325. }
  13326. // this.resetTextureCache();
  13327. texture.width = width;
  13328. texture.height = height;
  13329. texture.isReady = false;
  13330. texture.generateMipMaps = generateMipMaps;
  13331. texture.samplingMode = samplingMode;
  13332. this.updateTextureSamplingMode(samplingMode, texture);
  13333. this._internalTexturesCache.push(texture);
  13334. return texture;
  13335. };
  13336. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13337. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13338. if (texture.isCube) {
  13339. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13340. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13341. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13342. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13343. }
  13344. else if (texture.is3D) {
  13345. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13346. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13347. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13348. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13349. }
  13350. else {
  13351. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13352. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13353. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13354. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13355. }
  13356. texture.samplingMode = samplingMode;
  13357. };
  13358. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13359. if (premulAlpha === void 0) { premulAlpha = false; }
  13360. if (!texture) {
  13361. return;
  13362. }
  13363. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13364. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13365. if (premulAlpha) {
  13366. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13367. }
  13368. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13369. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13370. if (texture.generateMipMaps) {
  13371. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13372. }
  13373. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13374. if (premulAlpha) {
  13375. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13376. }
  13377. texture.isReady = true;
  13378. };
  13379. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13380. if (!texture || texture._isDisabled) {
  13381. return;
  13382. }
  13383. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13384. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13385. try {
  13386. // Testing video texture support
  13387. if (this._videoTextureSupported === undefined) {
  13388. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13389. if (this._gl.getError() !== 0) {
  13390. this._videoTextureSupported = false;
  13391. }
  13392. else {
  13393. this._videoTextureSupported = true;
  13394. }
  13395. }
  13396. // Copy video through the current working canvas if video texture is not supported
  13397. if (!this._videoTextureSupported) {
  13398. if (!texture._workingCanvas) {
  13399. texture._workingCanvas = document.createElement("canvas");
  13400. var context = texture._workingCanvas.getContext("2d");
  13401. if (!context) {
  13402. throw new Error("Unable to get 2d context");
  13403. }
  13404. texture._workingContext = context;
  13405. texture._workingCanvas.width = texture.width;
  13406. texture._workingCanvas.height = texture.height;
  13407. }
  13408. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13409. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13410. }
  13411. else {
  13412. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13413. }
  13414. if (texture.generateMipMaps) {
  13415. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13416. }
  13417. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13418. // this.resetTextureCache();
  13419. texture.isReady = true;
  13420. }
  13421. catch (ex) {
  13422. // Something unexpected
  13423. // Let's disable the texture
  13424. texture._isDisabled = true;
  13425. }
  13426. };
  13427. /**
  13428. * Updates a depth texture Comparison Mode and Function.
  13429. * If the comparison Function is equal to 0, the mode will be set to none.
  13430. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13431. * @param texture The texture to set the comparison function for
  13432. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13433. */
  13434. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13435. if (this.webGLVersion === 1) {
  13436. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13437. return;
  13438. }
  13439. var gl = this._gl;
  13440. if (texture.isCube) {
  13441. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13442. if (comparisonFunction === 0) {
  13443. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13444. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13445. }
  13446. else {
  13447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13448. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13449. }
  13450. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13451. }
  13452. else {
  13453. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13454. if (comparisonFunction === 0) {
  13455. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13456. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13457. }
  13458. else {
  13459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13461. }
  13462. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13463. }
  13464. texture._comparisonFunction = comparisonFunction;
  13465. };
  13466. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13467. var width = size.width || size;
  13468. var height = size.height || size;
  13469. internalTexture.baseWidth = width;
  13470. internalTexture.baseHeight = height;
  13471. internalTexture.width = width;
  13472. internalTexture.height = height;
  13473. internalTexture.isReady = true;
  13474. internalTexture.samples = 1;
  13475. internalTexture.generateMipMaps = false;
  13476. internalTexture._generateDepthBuffer = true;
  13477. internalTexture._generateStencilBuffer = generateStencil;
  13478. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13479. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13480. internalTexture._comparisonFunction = comparisonFunction;
  13481. var gl = this._gl;
  13482. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13483. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13484. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13485. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13486. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13487. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13488. if (comparisonFunction === 0) {
  13489. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13490. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13491. }
  13492. else {
  13493. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13494. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13495. }
  13496. };
  13497. /**
  13498. * Creates a depth stencil texture.
  13499. * This is only available in WebGL 2 or with the depth texture extension available.
  13500. * @param size The size of face edge in the texture.
  13501. * @param options The options defining the texture.
  13502. * @returns The texture
  13503. */
  13504. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13505. if (options.isCube) {
  13506. var width = size.width || size;
  13507. return this._createDepthStencilCubeTexture(width, options);
  13508. }
  13509. else {
  13510. return this._createDepthStencilTexture(size, options);
  13511. }
  13512. };
  13513. /**
  13514. * Creates a depth stencil texture.
  13515. * This is only available in WebGL 2 or with the depth texture extension available.
  13516. * @param size The size of face edge in the texture.
  13517. * @param options The options defining the texture.
  13518. * @returns The texture
  13519. */
  13520. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13521. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13522. if (!this._caps.depthTextureExtension) {
  13523. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13524. return internalTexture;
  13525. }
  13526. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13527. var gl = this._gl;
  13528. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13529. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13530. if (this.webGLVersion > 1) {
  13531. if (internalOptions.generateStencil) {
  13532. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13533. }
  13534. else {
  13535. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13536. }
  13537. }
  13538. else {
  13539. if (internalOptions.generateStencil) {
  13540. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13541. }
  13542. else {
  13543. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13544. }
  13545. }
  13546. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13547. return internalTexture;
  13548. };
  13549. /**
  13550. * Creates a depth stencil cube texture.
  13551. * This is only available in WebGL 2.
  13552. * @param size The size of face edge in the cube texture.
  13553. * @param options The options defining the cube texture.
  13554. * @returns The cube texture
  13555. */
  13556. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13557. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13558. internalTexture.isCube = true;
  13559. if (this.webGLVersion === 1) {
  13560. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13561. return internalTexture;
  13562. }
  13563. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13564. var gl = this._gl;
  13565. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13566. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13567. // Create the depth/stencil buffer
  13568. for (var face = 0; face < 6; face++) {
  13569. if (internalOptions.generateStencil) {
  13570. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13571. }
  13572. else {
  13573. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13574. }
  13575. }
  13576. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13577. return internalTexture;
  13578. };
  13579. /**
  13580. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13581. * @param renderTarget The render target to set the frame buffer for
  13582. */
  13583. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13584. // Create the framebuffer
  13585. var internalTexture = renderTarget.getInternalTexture();
  13586. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13587. return;
  13588. }
  13589. var gl = this._gl;
  13590. var depthStencilTexture = renderTarget.depthStencilTexture;
  13591. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13592. if (depthStencilTexture.isCube) {
  13593. if (depthStencilTexture._generateStencilBuffer) {
  13594. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13595. }
  13596. else {
  13597. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13598. }
  13599. }
  13600. else {
  13601. if (depthStencilTexture._generateStencilBuffer) {
  13602. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13603. }
  13604. else {
  13605. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13606. }
  13607. }
  13608. this.bindUnboundFramebuffer(null);
  13609. };
  13610. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13611. var fullOptions = new RenderTargetCreationOptions();
  13612. if (options !== undefined && typeof options === "object") {
  13613. fullOptions.generateMipMaps = options.generateMipMaps;
  13614. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13615. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13616. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13617. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13618. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13619. }
  13620. else {
  13621. fullOptions.generateMipMaps = options;
  13622. fullOptions.generateDepthBuffer = true;
  13623. fullOptions.generateStencilBuffer = false;
  13624. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13625. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13626. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13627. }
  13628. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13629. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13630. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13631. }
  13632. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13633. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13634. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13635. }
  13636. var gl = this._gl;
  13637. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13638. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13639. var width = size.width || size;
  13640. var height = size.height || size;
  13641. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13642. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13643. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13644. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13645. }
  13646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13649. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13650. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13651. // Create the framebuffer
  13652. var framebuffer = gl.createFramebuffer();
  13653. this.bindUnboundFramebuffer(framebuffer);
  13654. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13655. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13656. if (fullOptions.generateMipMaps) {
  13657. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13658. }
  13659. // Unbind
  13660. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13661. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13662. this.bindUnboundFramebuffer(null);
  13663. texture._framebuffer = framebuffer;
  13664. texture.baseWidth = width;
  13665. texture.baseHeight = height;
  13666. texture.width = width;
  13667. texture.height = height;
  13668. texture.isReady = true;
  13669. texture.samples = 1;
  13670. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13671. texture.samplingMode = fullOptions.samplingMode;
  13672. texture.type = fullOptions.type;
  13673. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13674. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13675. // this.resetTextureCache();
  13676. this._internalTexturesCache.push(texture);
  13677. return texture;
  13678. };
  13679. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13680. var generateMipMaps = false;
  13681. var generateDepthBuffer = true;
  13682. var generateStencilBuffer = false;
  13683. var generateDepthTexture = false;
  13684. var textureCount = 1;
  13685. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13686. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13687. var types = [], samplingModes = [];
  13688. if (options !== undefined) {
  13689. generateMipMaps = options.generateMipMaps;
  13690. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13691. generateStencilBuffer = options.generateStencilBuffer;
  13692. generateDepthTexture = options.generateDepthTexture;
  13693. textureCount = options.textureCount || 1;
  13694. if (options.types) {
  13695. types = options.types;
  13696. }
  13697. if (options.samplingModes) {
  13698. samplingModes = options.samplingModes;
  13699. }
  13700. }
  13701. var gl = this._gl;
  13702. // Create the framebuffer
  13703. var framebuffer = gl.createFramebuffer();
  13704. this.bindUnboundFramebuffer(framebuffer);
  13705. var width = size.width || size;
  13706. var height = size.height || size;
  13707. var textures = [];
  13708. var attachments = [];
  13709. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13710. for (var i = 0; i < textureCount; i++) {
  13711. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13712. var type = types[i] || defaultType;
  13713. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13714. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13715. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13716. }
  13717. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13718. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13719. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13720. }
  13721. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13722. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13723. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13724. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13725. }
  13726. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13727. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13728. textures.push(texture);
  13729. attachments.push(attachment);
  13730. gl.activeTexture(gl["TEXTURE" + i]);
  13731. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13732. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13733. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13735. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13736. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13737. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13738. if (generateMipMaps) {
  13739. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13740. }
  13741. // Unbind
  13742. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13743. texture._framebuffer = framebuffer;
  13744. texture._depthStencilBuffer = depthStencilBuffer;
  13745. texture.baseWidth = width;
  13746. texture.baseHeight = height;
  13747. texture.width = width;
  13748. texture.height = height;
  13749. texture.isReady = true;
  13750. texture.samples = 1;
  13751. texture.generateMipMaps = generateMipMaps;
  13752. texture.samplingMode = samplingMode;
  13753. texture.type = type;
  13754. texture._generateDepthBuffer = generateDepthBuffer;
  13755. texture._generateStencilBuffer = generateStencilBuffer;
  13756. texture._attachments = attachments;
  13757. this._internalTexturesCache.push(texture);
  13758. }
  13759. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13760. // Depth texture
  13761. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13762. gl.activeTexture(gl.TEXTURE0);
  13763. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13766. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13767. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13768. 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);
  13769. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13770. depthTexture._framebuffer = framebuffer;
  13771. depthTexture.baseWidth = width;
  13772. depthTexture.baseHeight = height;
  13773. depthTexture.width = width;
  13774. depthTexture.height = height;
  13775. depthTexture.isReady = true;
  13776. depthTexture.samples = 1;
  13777. depthTexture.generateMipMaps = generateMipMaps;
  13778. depthTexture.samplingMode = gl.NEAREST;
  13779. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13780. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13781. textures.push(depthTexture);
  13782. this._internalTexturesCache.push(depthTexture);
  13783. }
  13784. gl.drawBuffers(attachments);
  13785. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13786. this.bindUnboundFramebuffer(null);
  13787. this.resetTextureCache();
  13788. return textures;
  13789. };
  13790. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13791. if (samples === void 0) { samples = 1; }
  13792. var depthStencilBuffer = null;
  13793. var gl = this._gl;
  13794. // Create the depth/stencil buffer
  13795. if (generateStencilBuffer) {
  13796. depthStencilBuffer = gl.createRenderbuffer();
  13797. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13798. if (samples > 1) {
  13799. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13800. }
  13801. else {
  13802. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13803. }
  13804. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13805. }
  13806. else if (generateDepthBuffer) {
  13807. depthStencilBuffer = gl.createRenderbuffer();
  13808. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13809. if (samples > 1) {
  13810. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13811. }
  13812. else {
  13813. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13814. }
  13815. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13816. }
  13817. return depthStencilBuffer;
  13818. };
  13819. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13820. if (this.webGLVersion < 2 || !texture) {
  13821. return 1;
  13822. }
  13823. if (texture.samples === samples) {
  13824. return samples;
  13825. }
  13826. var gl = this._gl;
  13827. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13828. // Dispose previous render buffers
  13829. if (texture._depthStencilBuffer) {
  13830. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13831. texture._depthStencilBuffer = null;
  13832. }
  13833. if (texture._MSAAFramebuffer) {
  13834. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13835. texture._MSAAFramebuffer = null;
  13836. }
  13837. if (texture._MSAARenderBuffer) {
  13838. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13839. texture._MSAARenderBuffer = null;
  13840. }
  13841. if (samples > 1) {
  13842. var framebuffer = gl.createFramebuffer();
  13843. if (!framebuffer) {
  13844. throw new Error("Unable to create multi sampled framebuffer");
  13845. }
  13846. texture._MSAAFramebuffer = framebuffer;
  13847. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13848. var colorRenderbuffer = gl.createRenderbuffer();
  13849. if (!colorRenderbuffer) {
  13850. throw new Error("Unable to create multi sampled framebuffer");
  13851. }
  13852. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13853. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13854. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13855. texture._MSAARenderBuffer = colorRenderbuffer;
  13856. }
  13857. else {
  13858. this.bindUnboundFramebuffer(texture._framebuffer);
  13859. }
  13860. texture.samples = samples;
  13861. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13862. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13863. this.bindUnboundFramebuffer(null);
  13864. return samples;
  13865. };
  13866. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13867. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13868. return 1;
  13869. }
  13870. if (textures[0].samples === samples) {
  13871. return samples;
  13872. }
  13873. var gl = this._gl;
  13874. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13875. // Dispose previous render buffers
  13876. if (textures[0]._depthStencilBuffer) {
  13877. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13878. textures[0]._depthStencilBuffer = null;
  13879. }
  13880. if (textures[0]._MSAAFramebuffer) {
  13881. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13882. textures[0]._MSAAFramebuffer = null;
  13883. }
  13884. for (var i = 0; i < textures.length; i++) {
  13885. if (textures[i]._MSAARenderBuffer) {
  13886. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13887. textures[i]._MSAARenderBuffer = null;
  13888. }
  13889. }
  13890. if (samples > 1) {
  13891. var framebuffer = gl.createFramebuffer();
  13892. if (!framebuffer) {
  13893. throw new Error("Unable to create multi sampled framebuffer");
  13894. }
  13895. this.bindUnboundFramebuffer(framebuffer);
  13896. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13897. var attachments = [];
  13898. for (var i = 0; i < textures.length; i++) {
  13899. var texture = textures[i];
  13900. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13901. var colorRenderbuffer = gl.createRenderbuffer();
  13902. if (!colorRenderbuffer) {
  13903. throw new Error("Unable to create multi sampled framebuffer");
  13904. }
  13905. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13906. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13907. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13908. texture._MSAAFramebuffer = framebuffer;
  13909. texture._MSAARenderBuffer = colorRenderbuffer;
  13910. texture.samples = samples;
  13911. texture._depthStencilBuffer = depthStencilBuffer;
  13912. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13913. attachments.push(attachment);
  13914. }
  13915. gl.drawBuffers(attachments);
  13916. }
  13917. else {
  13918. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13919. }
  13920. this.bindUnboundFramebuffer(null);
  13921. return samples;
  13922. };
  13923. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13924. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13925. };
  13926. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13927. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13928. };
  13929. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13930. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13931. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13932. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13933. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13934. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13935. }
  13936. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13937. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13938. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13939. }
  13940. var gl = this._gl;
  13941. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13942. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13943. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13944. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13945. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13946. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13947. }
  13948. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13949. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13950. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13952. for (var face = 0; face < 6; face++) {
  13953. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13954. }
  13955. // Create the framebuffer
  13956. var framebuffer = gl.createFramebuffer();
  13957. this.bindUnboundFramebuffer(framebuffer);
  13958. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13959. // MipMaps
  13960. if (fullOptions.generateMipMaps) {
  13961. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13962. }
  13963. // Unbind
  13964. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13965. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13966. this.bindUnboundFramebuffer(null);
  13967. texture._framebuffer = framebuffer;
  13968. texture.width = size;
  13969. texture.height = size;
  13970. texture.isReady = true;
  13971. texture.isCube = true;
  13972. texture.samples = 1;
  13973. texture.generateMipMaps = fullOptions.generateMipMaps;
  13974. texture.samplingMode = fullOptions.samplingMode;
  13975. texture.type = fullOptions.type;
  13976. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13977. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13978. this._internalTexturesCache.push(texture);
  13979. return texture;
  13980. };
  13981. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13982. var _this = this;
  13983. if (onLoad === void 0) { onLoad = null; }
  13984. if (onError === void 0) { onError = null; }
  13985. if (forcedExtension === void 0) { forcedExtension = null; }
  13986. var callback = function (loadData) {
  13987. if (!loadData) {
  13988. if (onLoad) {
  13989. onLoad(null);
  13990. }
  13991. return;
  13992. }
  13993. var texture = loadData.texture;
  13994. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13995. texture._lodGenerationScale = scale;
  13996. texture._lodGenerationOffset = offset;
  13997. if (_this._caps.textureLOD) {
  13998. // Do not add extra process if texture lod is supported.
  13999. if (onLoad) {
  14000. onLoad(texture);
  14001. }
  14002. return;
  14003. }
  14004. var mipSlices = 3;
  14005. var gl = _this._gl;
  14006. var width = loadData.width;
  14007. if (!width) {
  14008. return;
  14009. }
  14010. var textures = [];
  14011. for (var i = 0; i < mipSlices; i++) {
  14012. //compute LOD from even spacing in smoothness (matching shader calculation)
  14013. var smoothness = i / (mipSlices - 1);
  14014. var roughness = 1 - smoothness;
  14015. var minLODIndex = offset; // roughness = 0
  14016. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14017. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14018. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14019. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14020. glTextureFromLod.isCube = true;
  14021. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14022. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14023. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14024. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14025. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14026. if (loadData.isDDS) {
  14027. var info = loadData.info;
  14028. var data = loadData.data;
  14029. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14030. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14031. }
  14032. else {
  14033. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14034. }
  14035. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14036. // Wrap in a base texture for easy binding.
  14037. var lodTexture = new BABYLON.BaseTexture(scene);
  14038. lodTexture.isCube = true;
  14039. lodTexture._texture = glTextureFromLod;
  14040. glTextureFromLod.isReady = true;
  14041. textures.push(lodTexture);
  14042. }
  14043. texture._lodTextureHigh = textures[2];
  14044. texture._lodTextureMid = textures[1];
  14045. texture._lodTextureLow = textures[0];
  14046. if (onLoad) {
  14047. onLoad(texture);
  14048. }
  14049. };
  14050. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14051. };
  14052. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14053. var _this = this;
  14054. if (onLoad === void 0) { onLoad = null; }
  14055. if (onError === void 0) { onError = null; }
  14056. if (forcedExtension === void 0) { forcedExtension = null; }
  14057. var gl = this._gl;
  14058. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14059. texture.isCube = true;
  14060. texture.url = rootUrl;
  14061. texture.generateMipMaps = !noMipmap;
  14062. if (!this._doNotHandleContextLost) {
  14063. texture._extension = forcedExtension;
  14064. texture._files = files;
  14065. }
  14066. var isKTX = false;
  14067. var isDDS = false;
  14068. var lastDot = rootUrl.lastIndexOf('.');
  14069. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14070. if (this._textureFormatInUse) {
  14071. extension = this._textureFormatInUse;
  14072. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14073. isKTX = true;
  14074. }
  14075. else {
  14076. isDDS = (extension === ".dds");
  14077. }
  14078. var onerror = function (request, exception) {
  14079. if (onError && request) {
  14080. onError(request.status + " " + request.statusText, exception);
  14081. }
  14082. };
  14083. if (isKTX) {
  14084. this._loadFile(rootUrl, function (data) {
  14085. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14086. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14087. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14088. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14089. ktx.uploadLevels(_this._gl, !noMipmap);
  14090. _this.setCubeMapTextureParams(gl, loadMipmap);
  14091. texture.width = ktx.pixelWidth;
  14092. texture.height = ktx.pixelHeight;
  14093. texture.isReady = true;
  14094. }, undefined, undefined, true, onerror);
  14095. }
  14096. else if (isDDS) {
  14097. if (files && files.length === 6) {
  14098. this._cascadeLoadFiles(scene, function (imgs) {
  14099. var info;
  14100. var loadMipmap = false;
  14101. var width = 0;
  14102. for (var index = 0; index < imgs.length; index++) {
  14103. var data = imgs[index];
  14104. info = BABYLON.DDSTools.GetDDSInfo(data);
  14105. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14106. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14107. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14108. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14109. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14110. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14111. }
  14112. texture.width = info.width;
  14113. texture.height = info.height;
  14114. texture.type = info.textureType;
  14115. width = info.width;
  14116. }
  14117. _this.setCubeMapTextureParams(gl, loadMipmap);
  14118. texture.isReady = true;
  14119. if (onLoad) {
  14120. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14121. }
  14122. }, files, onError);
  14123. }
  14124. else {
  14125. this._loadFile(rootUrl, function (data) {
  14126. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14127. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14128. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14129. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14130. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14131. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14132. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14133. }
  14134. _this.setCubeMapTextureParams(gl, loadMipmap);
  14135. texture.width = info.width;
  14136. texture.height = info.height;
  14137. texture.isReady = true;
  14138. texture.type = info.textureType;
  14139. if (onLoad) {
  14140. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14141. }
  14142. }, undefined, undefined, true, onerror);
  14143. }
  14144. }
  14145. else {
  14146. if (!files) {
  14147. throw new Error("Cannot load cubemap because files were not defined");
  14148. }
  14149. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14150. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14151. var height = width;
  14152. _this._prepareWorkingCanvas();
  14153. if (!_this._workingCanvas || !_this._workingContext) {
  14154. return;
  14155. }
  14156. _this._workingCanvas.width = width;
  14157. _this._workingCanvas.height = height;
  14158. var faces = [
  14159. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14160. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14161. ];
  14162. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14163. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14164. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14165. for (var index = 0; index < faces.length; index++) {
  14166. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14167. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14168. }
  14169. if (!noMipmap) {
  14170. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14171. }
  14172. _this.setCubeMapTextureParams(gl, !noMipmap);
  14173. texture.width = width;
  14174. texture.height = height;
  14175. texture.isReady = true;
  14176. if (format) {
  14177. texture.format = format;
  14178. }
  14179. texture.onLoadedObservable.notifyObservers(texture);
  14180. texture.onLoadedObservable.clear();
  14181. if (onLoad) {
  14182. onLoad();
  14183. }
  14184. }, files, onError);
  14185. }
  14186. this._internalTexturesCache.push(texture);
  14187. return texture;
  14188. };
  14189. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14190. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14193. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14194. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14195. // this.resetTextureCache();
  14196. };
  14197. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14198. if (compression === void 0) { compression = null; }
  14199. if (level === void 0) { level = 0; }
  14200. texture._bufferViewArray = data;
  14201. texture.format = format;
  14202. texture.type = type;
  14203. texture.invertY = invertY;
  14204. texture._compression = compression;
  14205. var gl = this._gl;
  14206. var textureType = this._getWebGLTextureType(type);
  14207. var internalFormat = this._getInternalFormat(format);
  14208. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14209. var needConversion = false;
  14210. if (internalFormat === gl.RGB) {
  14211. internalFormat = gl.RGBA;
  14212. needConversion = true;
  14213. }
  14214. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14215. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14216. if (texture.width % 4 !== 0) {
  14217. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14218. }
  14219. // Data are known to be in +X +Y +Z -X -Y -Z
  14220. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14221. var faceData = data[faceIndex];
  14222. if (compression) {
  14223. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14224. }
  14225. else {
  14226. if (needConversion) {
  14227. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14228. }
  14229. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14230. }
  14231. }
  14232. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14233. if (isPot && texture.generateMipMaps && level === 0) {
  14234. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14235. }
  14236. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14237. // this.resetTextureCache();
  14238. texture.isReady = true;
  14239. };
  14240. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14241. if (compression === void 0) { compression = null; }
  14242. var gl = this._gl;
  14243. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14244. texture.isCube = true;
  14245. texture.generateMipMaps = generateMipMaps;
  14246. texture.format = format;
  14247. texture.type = type;
  14248. if (!this._doNotHandleContextLost) {
  14249. texture._bufferViewArray = data;
  14250. }
  14251. var textureType = this._getWebGLTextureType(type);
  14252. var internalFormat = this._getInternalFormat(format);
  14253. if (internalFormat === gl.RGB) {
  14254. internalFormat = gl.RGBA;
  14255. }
  14256. var width = size;
  14257. var height = width;
  14258. texture.width = width;
  14259. texture.height = height;
  14260. // Double check on POT to generate Mips.
  14261. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14262. if (!isPot) {
  14263. generateMipMaps = false;
  14264. }
  14265. // Upload data if needed. The texture won't be ready until then.
  14266. if (data) {
  14267. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14268. }
  14269. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14270. // Filters
  14271. if (data && generateMipMaps) {
  14272. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14273. }
  14274. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14275. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14276. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14277. }
  14278. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14279. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14280. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14281. }
  14282. else {
  14283. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14285. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14286. }
  14287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14289. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14290. return texture;
  14291. };
  14292. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14293. var _this = this;
  14294. if (onLoad === void 0) { onLoad = null; }
  14295. if (onError === void 0) { onError = null; }
  14296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14297. if (invertY === void 0) { invertY = false; }
  14298. var gl = this._gl;
  14299. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14300. scene._addPendingData(texture);
  14301. texture.url = url;
  14302. this._internalTexturesCache.push(texture);
  14303. var onerror = function (request, exception) {
  14304. scene._removePendingData(texture);
  14305. if (onError && request) {
  14306. onError(request.status + " " + request.statusText, exception);
  14307. }
  14308. };
  14309. var internalCallback = function (data) {
  14310. var width = texture.width;
  14311. var faceDataArrays = callback(data);
  14312. if (!faceDataArrays) {
  14313. return;
  14314. }
  14315. if (mipmmapGenerator) {
  14316. var textureType = _this._getWebGLTextureType(type);
  14317. var internalFormat = _this._getInternalFormat(format);
  14318. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14319. var needConversion = false;
  14320. if (internalFormat === gl.RGB) {
  14321. internalFormat = gl.RGBA;
  14322. needConversion = true;
  14323. }
  14324. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14325. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14326. var mipData = mipmmapGenerator(faceDataArrays);
  14327. for (var level = 0; level < mipData.length; level++) {
  14328. var mipSize = width >> level;
  14329. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14330. var mipFaceData = mipData[level][faceIndex];
  14331. if (needConversion) {
  14332. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14333. }
  14334. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14335. }
  14336. }
  14337. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14338. }
  14339. else {
  14340. texture.generateMipMaps = !noMipmap;
  14341. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14342. }
  14343. texture.isReady = true;
  14344. // this.resetTextureCache();
  14345. scene._removePendingData(texture);
  14346. if (onLoad) {
  14347. onLoad();
  14348. }
  14349. };
  14350. this._loadFile(url, function (data) {
  14351. internalCallback(data);
  14352. }, undefined, scene.database, true, onerror);
  14353. return texture;
  14354. };
  14355. ;
  14356. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14357. if (compression === void 0) { compression = null; }
  14358. var internalFormat = this._getInternalFormat(format);
  14359. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14360. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14361. if (!this._doNotHandleContextLost) {
  14362. texture._bufferView = data;
  14363. texture.format = format;
  14364. texture.invertY = invertY;
  14365. texture._compression = compression;
  14366. }
  14367. if (texture.width % 4 !== 0) {
  14368. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14369. }
  14370. if (compression && data) {
  14371. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14372. }
  14373. else {
  14374. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14375. }
  14376. if (texture.generateMipMaps) {
  14377. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14378. }
  14379. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14380. // this.resetTextureCache();
  14381. texture.isReady = true;
  14382. };
  14383. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14384. if (compression === void 0) { compression = null; }
  14385. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14386. texture.baseWidth = width;
  14387. texture.baseHeight = height;
  14388. texture.baseDepth = depth;
  14389. texture.width = width;
  14390. texture.height = height;
  14391. texture.depth = depth;
  14392. texture.format = format;
  14393. texture.generateMipMaps = generateMipMaps;
  14394. texture.samplingMode = samplingMode;
  14395. texture.is3D = true;
  14396. if (!this._doNotHandleContextLost) {
  14397. texture._bufferView = data;
  14398. }
  14399. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14400. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14401. // Filters
  14402. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14403. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14404. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14405. if (generateMipMaps) {
  14406. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14407. }
  14408. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14409. this._internalTexturesCache.push(texture);
  14410. return texture;
  14411. };
  14412. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14413. var gl = this._gl;
  14414. if (!gl) {
  14415. return;
  14416. }
  14417. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14418. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14419. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14420. if (!noMipmap && !isCompressed) {
  14421. gl.generateMipmap(gl.TEXTURE_2D);
  14422. }
  14423. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14424. // this.resetTextureCache();
  14425. if (scene) {
  14426. scene._removePendingData(texture);
  14427. }
  14428. texture.onLoadedObservable.notifyObservers(texture);
  14429. texture.onLoadedObservable.clear();
  14430. };
  14431. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14432. var _this = this;
  14433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14434. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14435. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14436. var gl = this._gl;
  14437. if (!gl) {
  14438. return;
  14439. }
  14440. if (!texture._webGLTexture) {
  14441. // this.resetTextureCache();
  14442. if (scene) {
  14443. scene._removePendingData(texture);
  14444. }
  14445. return;
  14446. }
  14447. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14448. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14449. texture.baseWidth = width;
  14450. texture.baseHeight = height;
  14451. texture.width = potWidth;
  14452. texture.height = potHeight;
  14453. texture.isReady = true;
  14454. if (processFunction(potWidth, potHeight, function () {
  14455. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14456. })) {
  14457. // Returning as texture needs extra async steps
  14458. return;
  14459. }
  14460. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14461. };
  14462. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14463. // Create new RGBA data container.
  14464. var rgbaData;
  14465. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14466. rgbaData = new Float32Array(width * height * 4);
  14467. }
  14468. else {
  14469. rgbaData = new Uint32Array(width * height * 4);
  14470. }
  14471. // Convert each pixel.
  14472. for (var x = 0; x < width; x++) {
  14473. for (var y = 0; y < height; y++) {
  14474. var index = (y * width + x) * 3;
  14475. var newIndex = (y * width + x) * 4;
  14476. // Map Old Value to new value.
  14477. rgbaData[newIndex + 0] = rgbData[index + 0];
  14478. rgbaData[newIndex + 1] = rgbData[index + 1];
  14479. rgbaData[newIndex + 2] = rgbData[index + 2];
  14480. // Add fully opaque alpha channel.
  14481. rgbaData[newIndex + 3] = 1;
  14482. }
  14483. }
  14484. return rgbaData;
  14485. };
  14486. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14487. var gl = this._gl;
  14488. if (texture._framebuffer) {
  14489. gl.deleteFramebuffer(texture._framebuffer);
  14490. texture._framebuffer = null;
  14491. }
  14492. if (texture._depthStencilBuffer) {
  14493. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14494. texture._depthStencilBuffer = null;
  14495. }
  14496. if (texture._MSAAFramebuffer) {
  14497. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14498. texture._MSAAFramebuffer = null;
  14499. }
  14500. if (texture._MSAARenderBuffer) {
  14501. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14502. texture._MSAARenderBuffer = null;
  14503. }
  14504. };
  14505. Engine.prototype._releaseTexture = function (texture) {
  14506. var gl = this._gl;
  14507. this._releaseFramebufferObjects(texture);
  14508. gl.deleteTexture(texture._webGLTexture);
  14509. // Unbind channels
  14510. this.unbindAllTextures();
  14511. var index = this._internalTexturesCache.indexOf(texture);
  14512. if (index !== -1) {
  14513. this._internalTexturesCache.splice(index, 1);
  14514. }
  14515. // Integrated fixed lod samplers.
  14516. if (texture._lodTextureHigh) {
  14517. texture._lodTextureHigh.dispose();
  14518. }
  14519. if (texture._lodTextureMid) {
  14520. texture._lodTextureMid.dispose();
  14521. }
  14522. if (texture._lodTextureLow) {
  14523. texture._lodTextureLow.dispose();
  14524. }
  14525. // Set output texture of post process to null if the texture has been released/disposed
  14526. this.scenes.forEach(function (scene) {
  14527. scene.postProcesses.forEach(function (postProcess) {
  14528. if (postProcess._outputTexture == texture) {
  14529. postProcess._outputTexture = null;
  14530. }
  14531. });
  14532. scene.cameras.forEach(function (camera) {
  14533. camera._postProcesses.forEach(function (postProcess) {
  14534. if (postProcess) {
  14535. if (postProcess._outputTexture == texture) {
  14536. postProcess._outputTexture = null;
  14537. }
  14538. }
  14539. });
  14540. });
  14541. });
  14542. };
  14543. Engine.prototype.setProgram = function (program) {
  14544. if (this._currentProgram !== program) {
  14545. this._gl.useProgram(program);
  14546. this._currentProgram = program;
  14547. }
  14548. };
  14549. Engine.prototype.bindSamplers = function (effect) {
  14550. this.setProgram(effect.getProgram());
  14551. var samplers = effect.getSamplers();
  14552. for (var index = 0; index < samplers.length; index++) {
  14553. var uniform = effect.getUniform(samplers[index]);
  14554. if (uniform) {
  14555. this._boundUniforms[index] = uniform;
  14556. }
  14557. }
  14558. this._currentEffect = null;
  14559. };
  14560. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14561. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14562. return;
  14563. }
  14564. // Remove
  14565. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14566. // Bind last to it
  14567. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14568. // Bind to dummy
  14569. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14570. };
  14571. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14572. if (!internalTexture) {
  14573. return -1;
  14574. }
  14575. internalTexture._initialSlot = channel;
  14576. if (this.disableTextureBindingOptimization) {
  14577. if (channel !== internalTexture._designatedSlot) {
  14578. this._textureCollisions.addCount(1, false);
  14579. }
  14580. }
  14581. else {
  14582. if (channel !== internalTexture._designatedSlot) {
  14583. if (internalTexture._designatedSlot > -1) {
  14584. return internalTexture._designatedSlot;
  14585. }
  14586. else {
  14587. // No slot for this texture, let's pick a new one (if we find a free slot)
  14588. if (this._nextFreeTextureSlots.length) {
  14589. return this._nextFreeTextureSlots[0];
  14590. }
  14591. // We need to recycle the oldest bound texture, sorry.
  14592. this._textureCollisions.addCount(1, false);
  14593. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14594. }
  14595. }
  14596. }
  14597. return channel;
  14598. };
  14599. Engine.prototype._linkTrackers = function (previous, next) {
  14600. previous.next = next;
  14601. next.previous = previous;
  14602. };
  14603. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14604. var currentSlot = internalTexture._designatedSlot;
  14605. if (currentSlot === -1) {
  14606. return -1;
  14607. }
  14608. internalTexture._designatedSlot = -1;
  14609. if (this.disableTextureBindingOptimization) {
  14610. return -1;
  14611. }
  14612. // Remove from bound list
  14613. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14614. // Free the slot
  14615. this._boundTexturesCache[currentSlot] = null;
  14616. this._nextFreeTextureSlots.push(currentSlot);
  14617. return currentSlot;
  14618. };
  14619. Engine.prototype._activateCurrentTexture = function () {
  14620. if (this._currentTextureChannel !== this._activeChannel) {
  14621. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14622. this._currentTextureChannel = this._activeChannel;
  14623. }
  14624. };
  14625. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14626. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14627. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14628. this._activeChannel = texture._designatedSlot;
  14629. }
  14630. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14631. var isTextureForRendering = texture && texture._initialSlot > -1;
  14632. if (currentTextureBound !== texture) {
  14633. if (currentTextureBound) {
  14634. this._removeDesignatedSlot(currentTextureBound);
  14635. }
  14636. this._activateCurrentTexture();
  14637. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14638. this._boundTexturesCache[this._activeChannel] = texture;
  14639. if (texture) {
  14640. if (!this.disableTextureBindingOptimization) {
  14641. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14642. if (slotIndex > -1) {
  14643. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14644. }
  14645. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14646. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14647. }
  14648. texture._designatedSlot = this._activeChannel;
  14649. }
  14650. }
  14651. else if (forTextureDataUpdate) {
  14652. this._activateCurrentTexture();
  14653. }
  14654. if (isTextureForRendering && !forTextureDataUpdate) {
  14655. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14656. }
  14657. };
  14658. Engine.prototype._bindTexture = function (channel, texture) {
  14659. if (channel < 0) {
  14660. return;
  14661. }
  14662. if (texture) {
  14663. channel = this._getCorrectTextureChannel(channel, texture);
  14664. }
  14665. this._activeChannel = channel;
  14666. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14667. };
  14668. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14669. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14670. };
  14671. /**
  14672. * Binds the output of the passed in post process to the texture channel specified
  14673. * @param channel The channel the texture should be bound to
  14674. * @param postProcess The post process which's output should be bound
  14675. */
  14676. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14677. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14678. };
  14679. Engine.prototype.unbindAllTextures = function () {
  14680. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14681. this._activeChannel = channel;
  14682. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14683. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14684. if (this.webGLVersion > 1) {
  14685. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14686. }
  14687. }
  14688. };
  14689. /**
  14690. * Sets a texture to the according uniform.
  14691. * @param channel The texture channel
  14692. * @param uniform The uniform to set
  14693. * @param texture The texture to apply
  14694. */
  14695. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14696. if (channel < 0) {
  14697. return;
  14698. }
  14699. if (uniform) {
  14700. this._boundUniforms[channel] = uniform;
  14701. }
  14702. this._setTexture(channel, texture);
  14703. };
  14704. /**
  14705. * Sets a depth stencil texture from a render target to the according uniform.
  14706. * @param channel The texture channel
  14707. * @param uniform The uniform to set
  14708. * @param texture The render target texture containing the depth stencil texture to apply
  14709. */
  14710. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14711. if (channel < 0) {
  14712. return;
  14713. }
  14714. if (uniform) {
  14715. this._boundUniforms[channel] = uniform;
  14716. }
  14717. if (!texture || !texture.depthStencilTexture) {
  14718. this._setTexture(channel, null);
  14719. }
  14720. else {
  14721. this._setTexture(channel, texture, false, true);
  14722. }
  14723. };
  14724. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14725. var uniform = this._boundUniforms[sourceSlot];
  14726. if (uniform._currentState === destination) {
  14727. return;
  14728. }
  14729. this._gl.uniform1i(uniform, destination);
  14730. uniform._currentState = destination;
  14731. };
  14732. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14733. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14734. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14735. // Not ready?
  14736. if (!texture) {
  14737. if (this._boundTexturesCache[channel] != null) {
  14738. this._activeChannel = channel;
  14739. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14740. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14741. if (this.webGLVersion > 1) {
  14742. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14743. }
  14744. }
  14745. return false;
  14746. }
  14747. // Video
  14748. if (texture.video) {
  14749. this._activeChannel = channel;
  14750. texture.update();
  14751. }
  14752. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14753. texture.delayLoad();
  14754. return false;
  14755. }
  14756. var internalTexture;
  14757. if (depthStencilTexture) {
  14758. internalTexture = texture.depthStencilTexture;
  14759. }
  14760. else if (texture.isReady()) {
  14761. internalTexture = texture.getInternalTexture();
  14762. }
  14763. else if (texture.isCube) {
  14764. internalTexture = this.emptyCubeTexture;
  14765. }
  14766. else if (texture.is3D) {
  14767. internalTexture = this.emptyTexture3D;
  14768. }
  14769. else {
  14770. internalTexture = this.emptyTexture;
  14771. }
  14772. if (!isPartOfTextureArray) {
  14773. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14774. }
  14775. if (this._boundTexturesCache[channel] === internalTexture) {
  14776. this._moveBoundTextureOnTop(internalTexture);
  14777. if (!isPartOfTextureArray) {
  14778. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14779. }
  14780. return false;
  14781. }
  14782. this._activeChannel = channel;
  14783. if (internalTexture && internalTexture.is3D) {
  14784. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14785. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14786. internalTexture._cachedWrapU = texture.wrapU;
  14787. switch (texture.wrapU) {
  14788. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14789. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14790. break;
  14791. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14792. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14793. break;
  14794. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14795. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14796. break;
  14797. }
  14798. }
  14799. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14800. internalTexture._cachedWrapV = texture.wrapV;
  14801. switch (texture.wrapV) {
  14802. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14803. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14804. break;
  14805. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14806. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14807. break;
  14808. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14809. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14810. break;
  14811. }
  14812. }
  14813. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14814. internalTexture._cachedWrapR = texture.wrapR;
  14815. switch (texture.wrapR) {
  14816. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14817. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14818. break;
  14819. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14820. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14821. break;
  14822. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14823. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14824. break;
  14825. }
  14826. }
  14827. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14828. }
  14829. else if (internalTexture && internalTexture.isCube) {
  14830. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14831. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14832. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14833. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14834. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14835. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14836. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14837. }
  14838. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14839. }
  14840. else {
  14841. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14842. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14843. internalTexture._cachedWrapU = texture.wrapU;
  14844. switch (texture.wrapU) {
  14845. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14846. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14847. break;
  14848. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14849. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14850. break;
  14851. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14852. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14853. break;
  14854. }
  14855. }
  14856. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14857. internalTexture._cachedWrapV = texture.wrapV;
  14858. switch (texture.wrapV) {
  14859. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14860. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14861. break;
  14862. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14863. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14864. break;
  14865. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14866. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14867. break;
  14868. }
  14869. }
  14870. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14871. }
  14872. return true;
  14873. };
  14874. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14875. if (channel < 0 || !uniform) {
  14876. return;
  14877. }
  14878. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14879. this._textureUnits = new Int32Array(textures.length);
  14880. }
  14881. for (var i = 0; i < textures.length; i++) {
  14882. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14883. }
  14884. this._gl.uniform1iv(uniform, this._textureUnits);
  14885. for (var index = 0; index < textures.length; index++) {
  14886. this._setTexture(this._textureUnits[index], textures[index], true);
  14887. }
  14888. };
  14889. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14890. var internalTexture = texture.getInternalTexture();
  14891. if (!internalTexture) {
  14892. return;
  14893. }
  14894. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14895. var value = texture.anisotropicFilteringLevel;
  14896. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14897. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14898. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14899. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14900. }
  14901. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14902. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14903. internalTexture._cachedAnisotropicFilteringLevel = value;
  14904. }
  14905. };
  14906. Engine.prototype.readPixels = function (x, y, width, height) {
  14907. var data = new Uint8Array(height * width * 4);
  14908. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14909. return data;
  14910. };
  14911. /**
  14912. * Add an externaly attached data from its key.
  14913. * This method call will fail and return false, if such key already exists.
  14914. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14915. * @param key the unique key that identifies the data
  14916. * @param data the data object to associate to the key for this Engine instance
  14917. * @return true if no such key were already present and the data was added successfully, false otherwise
  14918. */
  14919. Engine.prototype.addExternalData = function (key, data) {
  14920. if (!this._externalData) {
  14921. this._externalData = new BABYLON.StringDictionary();
  14922. }
  14923. return this._externalData.add(key, data);
  14924. };
  14925. /**
  14926. * Get an externaly attached data from its key
  14927. * @param key the unique key that identifies the data
  14928. * @return the associated data, if present (can be null), or undefined if not present
  14929. */
  14930. Engine.prototype.getExternalData = function (key) {
  14931. if (!this._externalData) {
  14932. this._externalData = new BABYLON.StringDictionary();
  14933. }
  14934. return this._externalData.get(key);
  14935. };
  14936. /**
  14937. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14938. * @param key the unique key that identifies the data
  14939. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14940. * @return the associated data, can be null if the factory returned null.
  14941. */
  14942. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14943. if (!this._externalData) {
  14944. this._externalData = new BABYLON.StringDictionary();
  14945. }
  14946. return this._externalData.getOrAddWithFactory(key, factory);
  14947. };
  14948. /**
  14949. * Remove an externaly attached data from the Engine instance
  14950. * @param key the unique key that identifies the data
  14951. * @return true if the data was successfully removed, false if it doesn't exist
  14952. */
  14953. Engine.prototype.removeExternalData = function (key) {
  14954. if (!this._externalData) {
  14955. this._externalData = new BABYLON.StringDictionary();
  14956. }
  14957. return this._externalData.remove(key);
  14958. };
  14959. Engine.prototype.unbindAllAttributes = function () {
  14960. if (this._mustWipeVertexAttributes) {
  14961. this._mustWipeVertexAttributes = false;
  14962. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14963. this._gl.disableVertexAttribArray(i);
  14964. this._vertexAttribArraysEnabled[i] = false;
  14965. this._currentBufferPointers[i].active = false;
  14966. }
  14967. return;
  14968. }
  14969. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14970. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14971. continue;
  14972. }
  14973. this._gl.disableVertexAttribArray(i);
  14974. this._vertexAttribArraysEnabled[i] = false;
  14975. this._currentBufferPointers[i].active = false;
  14976. }
  14977. };
  14978. Engine.prototype.releaseEffects = function () {
  14979. for (var name in this._compiledEffects) {
  14980. this._deleteProgram(this._compiledEffects[name]._program);
  14981. }
  14982. this._compiledEffects = {};
  14983. };
  14984. // Dispose
  14985. Engine.prototype.dispose = function () {
  14986. this.hideLoadingUI();
  14987. this.stopRenderLoop();
  14988. // Release postProcesses
  14989. while (this.postProcesses.length) {
  14990. this.postProcesses[0].dispose();
  14991. }
  14992. // Empty texture
  14993. if (this._emptyTexture) {
  14994. this._releaseTexture(this._emptyTexture);
  14995. this._emptyTexture = null;
  14996. }
  14997. if (this._emptyCubeTexture) {
  14998. this._releaseTexture(this._emptyCubeTexture);
  14999. this._emptyCubeTexture = null;
  15000. }
  15001. // Rescale PP
  15002. if (this._rescalePostProcess) {
  15003. this._rescalePostProcess.dispose();
  15004. }
  15005. // Release scenes
  15006. while (this.scenes.length) {
  15007. this.scenes[0].dispose();
  15008. }
  15009. // Release audio engine
  15010. if (Engine.audioEngine) {
  15011. Engine.audioEngine.dispose();
  15012. }
  15013. // Release effects
  15014. this.releaseEffects();
  15015. // Unbind
  15016. this.unbindAllAttributes();
  15017. this._boundUniforms = [];
  15018. if (this._dummyFramebuffer) {
  15019. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15020. }
  15021. //WebVR
  15022. this.disableVR();
  15023. // Events
  15024. if (BABYLON.Tools.IsWindowObjectExist()) {
  15025. window.removeEventListener("blur", this._onBlur);
  15026. window.removeEventListener("focus", this._onFocus);
  15027. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15028. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15029. if (this._renderingCanvas) {
  15030. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15031. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15032. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15033. if (!this._doNotHandleContextLost) {
  15034. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15035. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15036. }
  15037. }
  15038. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15039. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15040. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15041. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15042. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15043. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15044. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15045. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15046. if (this._onVrDisplayConnect) {
  15047. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15048. if (this._onVrDisplayDisconnect) {
  15049. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15050. }
  15051. if (this._onVrDisplayPresentChange) {
  15052. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15053. }
  15054. this._onVrDisplayConnect = null;
  15055. this._onVrDisplayDisconnect = null;
  15056. }
  15057. }
  15058. // Remove from Instances
  15059. var index = Engine.Instances.indexOf(this);
  15060. if (index >= 0) {
  15061. Engine.Instances.splice(index, 1);
  15062. }
  15063. this._workingCanvas = null;
  15064. this._workingContext = null;
  15065. this._currentBufferPointers = [];
  15066. this._renderingCanvas = null;
  15067. this._currentProgram = null;
  15068. this._bindedRenderFunction = null;
  15069. this.onResizeObservable.clear();
  15070. this.onCanvasBlurObservable.clear();
  15071. this.onCanvasFocusObservable.clear();
  15072. this.onCanvasPointerOutObservable.clear();
  15073. this.onBeginFrameObservable.clear();
  15074. this.onEndFrameObservable.clear();
  15075. BABYLON.Effect.ResetCache();
  15076. // Abort active requests
  15077. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15078. var request = _a[_i];
  15079. request.abort();
  15080. }
  15081. };
  15082. // Loading screen
  15083. Engine.prototype.displayLoadingUI = function () {
  15084. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15085. return;
  15086. }
  15087. var loadingScreen = this.loadingScreen;
  15088. if (loadingScreen) {
  15089. loadingScreen.displayLoadingUI();
  15090. }
  15091. };
  15092. Engine.prototype.hideLoadingUI = function () {
  15093. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15094. return;
  15095. }
  15096. var loadingScreen = this.loadingScreen;
  15097. if (loadingScreen) {
  15098. loadingScreen.hideLoadingUI();
  15099. }
  15100. };
  15101. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15102. get: function () {
  15103. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15104. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15105. return this._loadingScreen;
  15106. },
  15107. set: function (loadingScreen) {
  15108. this._loadingScreen = loadingScreen;
  15109. },
  15110. enumerable: true,
  15111. configurable: true
  15112. });
  15113. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15114. set: function (text) {
  15115. this.loadingScreen.loadingUIText = text;
  15116. },
  15117. enumerable: true,
  15118. configurable: true
  15119. });
  15120. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15121. set: function (color) {
  15122. this.loadingScreen.loadingUIBackgroundColor = color;
  15123. },
  15124. enumerable: true,
  15125. configurable: true
  15126. });
  15127. Engine.prototype.attachContextLostEvent = function (callback) {
  15128. if (this._renderingCanvas) {
  15129. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15130. }
  15131. };
  15132. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15133. if (this._renderingCanvas) {
  15134. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15135. }
  15136. };
  15137. Engine.prototype.getVertexShaderSource = function (program) {
  15138. var shaders = this._gl.getAttachedShaders(program);
  15139. if (!shaders) {
  15140. return null;
  15141. }
  15142. return this._gl.getShaderSource(shaders[0]);
  15143. };
  15144. Engine.prototype.getFragmentShaderSource = function (program) {
  15145. var shaders = this._gl.getAttachedShaders(program);
  15146. if (!shaders) {
  15147. return null;
  15148. }
  15149. return this._gl.getShaderSource(shaders[1]);
  15150. };
  15151. Engine.prototype.getError = function () {
  15152. return this._gl.getError();
  15153. };
  15154. // FPS
  15155. Engine.prototype.getFps = function () {
  15156. return this._fps;
  15157. };
  15158. Engine.prototype.getDeltaTime = function () {
  15159. return this._deltaTime;
  15160. };
  15161. Engine.prototype._measureFps = function () {
  15162. this._performanceMonitor.sampleFrame();
  15163. this._fps = this._performanceMonitor.averageFPS;
  15164. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15165. };
  15166. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15167. if (faceIndex === void 0) { faceIndex = -1; }
  15168. var gl = this._gl;
  15169. if (!this._dummyFramebuffer) {
  15170. var dummy = gl.createFramebuffer();
  15171. if (!dummy) {
  15172. throw new Error("Unable to create dummy framebuffer");
  15173. }
  15174. this._dummyFramebuffer = dummy;
  15175. }
  15176. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15177. if (faceIndex > -1) {
  15178. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15179. }
  15180. else {
  15181. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15182. }
  15183. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15184. var buffer;
  15185. switch (readType) {
  15186. case gl.UNSIGNED_BYTE:
  15187. buffer = new Uint8Array(4 * width * height);
  15188. readType = gl.UNSIGNED_BYTE;
  15189. break;
  15190. default:
  15191. buffer = new Float32Array(4 * width * height);
  15192. readType = gl.FLOAT;
  15193. break;
  15194. }
  15195. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15196. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15197. return buffer;
  15198. };
  15199. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15200. if (this._webGLVersion > 1) {
  15201. return this._caps.colorBufferFloat;
  15202. }
  15203. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15204. };
  15205. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15206. if (this._webGLVersion > 1) {
  15207. return this._caps.colorBufferFloat;
  15208. }
  15209. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15210. };
  15211. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15212. Engine.prototype._canRenderToFramebuffer = function (type) {
  15213. var gl = this._gl;
  15214. //clear existing errors
  15215. while (gl.getError() !== gl.NO_ERROR) { }
  15216. var successful = true;
  15217. var texture = gl.createTexture();
  15218. gl.bindTexture(gl.TEXTURE_2D, texture);
  15219. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15220. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15221. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15222. var fb = gl.createFramebuffer();
  15223. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15224. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15225. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15226. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15227. successful = successful && (gl.getError() === gl.NO_ERROR);
  15228. //try render by clearing frame buffer's color buffer
  15229. if (successful) {
  15230. gl.clear(gl.COLOR_BUFFER_BIT);
  15231. successful = successful && (gl.getError() === gl.NO_ERROR);
  15232. }
  15233. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15234. if (successful) {
  15235. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15236. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15237. var readFormat = gl.RGBA;
  15238. var readType = gl.UNSIGNED_BYTE;
  15239. var buffer = new Uint8Array(4);
  15240. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15241. successful = successful && (gl.getError() === gl.NO_ERROR);
  15242. }
  15243. //clean up
  15244. gl.deleteTexture(texture);
  15245. gl.deleteFramebuffer(fb);
  15246. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15247. //clear accumulated errors
  15248. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15249. return successful;
  15250. };
  15251. Engine.prototype._getWebGLTextureType = function (type) {
  15252. if (type === Engine.TEXTURETYPE_FLOAT) {
  15253. return this._gl.FLOAT;
  15254. }
  15255. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15256. // Add Half Float Constant.
  15257. return this._gl.HALF_FLOAT_OES;
  15258. }
  15259. return this._gl.UNSIGNED_BYTE;
  15260. };
  15261. ;
  15262. Engine.prototype._getInternalFormat = function (format) {
  15263. var internalFormat = this._gl.RGBA;
  15264. switch (format) {
  15265. case Engine.TEXTUREFORMAT_ALPHA:
  15266. internalFormat = this._gl.ALPHA;
  15267. break;
  15268. case Engine.TEXTUREFORMAT_LUMINANCE:
  15269. internalFormat = this._gl.LUMINANCE;
  15270. break;
  15271. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15272. internalFormat = this._gl.LUMINANCE_ALPHA;
  15273. break;
  15274. case Engine.TEXTUREFORMAT_RGB:
  15275. case Engine.TEXTUREFORMAT_RGB32F:
  15276. internalFormat = this._gl.RGB;
  15277. break;
  15278. case Engine.TEXTUREFORMAT_RGBA:
  15279. case Engine.TEXTUREFORMAT_RGBA32F:
  15280. internalFormat = this._gl.RGBA;
  15281. break;
  15282. case Engine.TEXTUREFORMAT_R32F:
  15283. internalFormat = this._gl.RED;
  15284. break;
  15285. case Engine.TEXTUREFORMAT_RG32F:
  15286. internalFormat = this._gl.RG;
  15287. break;
  15288. }
  15289. return internalFormat;
  15290. };
  15291. /** @ignore */
  15292. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15293. if (this._webGLVersion === 1) {
  15294. if (format) {
  15295. switch (format) {
  15296. case Engine.TEXTUREFORMAT_LUMINANCE:
  15297. return this._gl.LUMINANCE;
  15298. }
  15299. }
  15300. return this._gl.RGBA;
  15301. }
  15302. if (type === Engine.TEXTURETYPE_FLOAT) {
  15303. if (format) {
  15304. switch (format) {
  15305. case Engine.TEXTUREFORMAT_R32F:
  15306. return this._gl.R32F;
  15307. case Engine.TEXTUREFORMAT_RG32F:
  15308. return this._gl.RG32F;
  15309. case Engine.TEXTUREFORMAT_RGB32F:
  15310. return this._gl.RGB32F;
  15311. }
  15312. }
  15313. return this._gl.RGBA32F;
  15314. }
  15315. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15316. return this._gl.RGBA16F;
  15317. }
  15318. if (format) {
  15319. switch (format) {
  15320. case Engine.TEXTUREFORMAT_LUMINANCE:
  15321. return this._gl.LUMINANCE;
  15322. }
  15323. }
  15324. return this._gl.RGBA;
  15325. };
  15326. ;
  15327. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15328. if (type === Engine.TEXTURETYPE_FLOAT) {
  15329. return this._gl.RGBA32F;
  15330. }
  15331. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15332. return this._gl.RGBA16F;
  15333. }
  15334. return this._gl.RGBA8;
  15335. };
  15336. ;
  15337. Engine.prototype.createQuery = function () {
  15338. return this._gl.createQuery();
  15339. };
  15340. Engine.prototype.deleteQuery = function (query) {
  15341. this._gl.deleteQuery(query);
  15342. return this;
  15343. };
  15344. Engine.prototype.isQueryResultAvailable = function (query) {
  15345. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15346. };
  15347. Engine.prototype.getQueryResult = function (query) {
  15348. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15349. };
  15350. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15351. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15352. this._gl.beginQuery(glAlgorithm, query);
  15353. return this;
  15354. };
  15355. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15356. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15357. this._gl.endQuery(glAlgorithm);
  15358. return this;
  15359. };
  15360. /* Time queries */
  15361. Engine.prototype._createTimeQuery = function () {
  15362. var timerQuery = this._caps.timerQuery;
  15363. if (timerQuery.createQueryEXT) {
  15364. return timerQuery.createQueryEXT();
  15365. }
  15366. return this.createQuery();
  15367. };
  15368. Engine.prototype._deleteTimeQuery = function (query) {
  15369. var timerQuery = this._caps.timerQuery;
  15370. if (timerQuery.deleteQueryEXT) {
  15371. timerQuery.deleteQueryEXT(query);
  15372. return;
  15373. }
  15374. this.deleteQuery(query);
  15375. };
  15376. Engine.prototype._getTimeQueryResult = function (query) {
  15377. var timerQuery = this._caps.timerQuery;
  15378. if (timerQuery.getQueryObjectEXT) {
  15379. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15380. }
  15381. return this.getQueryResult(query);
  15382. };
  15383. Engine.prototype._getTimeQueryAvailability = function (query) {
  15384. var timerQuery = this._caps.timerQuery;
  15385. if (timerQuery.getQueryObjectEXT) {
  15386. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15387. }
  15388. return this.isQueryResultAvailable(query);
  15389. };
  15390. Engine.prototype.startTimeQuery = function () {
  15391. var timerQuery = this._caps.timerQuery;
  15392. if (!timerQuery) {
  15393. return null;
  15394. }
  15395. var token = new BABYLON._TimeToken();
  15396. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15397. if (this._caps.canUseTimestampForTimerQuery) {
  15398. token._startTimeQuery = this._createTimeQuery();
  15399. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15400. }
  15401. else {
  15402. if (this._currentNonTimestampToken) {
  15403. return this._currentNonTimestampToken;
  15404. }
  15405. token._timeElapsedQuery = this._createTimeQuery();
  15406. if (timerQuery.beginQueryEXT) {
  15407. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15408. }
  15409. else {
  15410. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15411. }
  15412. this._currentNonTimestampToken = token;
  15413. }
  15414. return token;
  15415. };
  15416. Engine.prototype.endTimeQuery = function (token) {
  15417. var timerQuery = this._caps.timerQuery;
  15418. if (!timerQuery || !token) {
  15419. return -1;
  15420. }
  15421. if (this._caps.canUseTimestampForTimerQuery) {
  15422. if (!token._startTimeQuery) {
  15423. return -1;
  15424. }
  15425. if (!token._endTimeQuery) {
  15426. token._endTimeQuery = this._createTimeQuery();
  15427. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15428. }
  15429. }
  15430. else if (!token._timeElapsedQueryEnded) {
  15431. if (!token._timeElapsedQuery) {
  15432. return -1;
  15433. }
  15434. if (timerQuery.endQueryEXT) {
  15435. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15436. }
  15437. else {
  15438. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15439. }
  15440. token._timeElapsedQueryEnded = true;
  15441. }
  15442. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15443. var available = false;
  15444. if (token._endTimeQuery) {
  15445. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15446. }
  15447. else if (token._timeElapsedQuery) {
  15448. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15449. }
  15450. if (available && !disjoint) {
  15451. var result = 0;
  15452. if (this._caps.canUseTimestampForTimerQuery) {
  15453. if (!token._startTimeQuery || !token._endTimeQuery) {
  15454. return -1;
  15455. }
  15456. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15457. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15458. result = timeEnd - timeStart;
  15459. this._deleteTimeQuery(token._startTimeQuery);
  15460. this._deleteTimeQuery(token._endTimeQuery);
  15461. token._startTimeQuery = null;
  15462. token._endTimeQuery = null;
  15463. }
  15464. else {
  15465. if (!token._timeElapsedQuery) {
  15466. return -1;
  15467. }
  15468. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15469. this._deleteTimeQuery(token._timeElapsedQuery);
  15470. token._timeElapsedQuery = null;
  15471. token._timeElapsedQueryEnded = false;
  15472. this._currentNonTimestampToken = null;
  15473. }
  15474. return result;
  15475. }
  15476. return -1;
  15477. };
  15478. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15479. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15480. };
  15481. // Transform feedback
  15482. Engine.prototype.createTransformFeedback = function () {
  15483. return this._gl.createTransformFeedback();
  15484. };
  15485. Engine.prototype.deleteTransformFeedback = function (value) {
  15486. this._gl.deleteTransformFeedback(value);
  15487. };
  15488. Engine.prototype.bindTransformFeedback = function (value) {
  15489. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15490. };
  15491. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15492. if (usePoints === void 0) { usePoints = true; }
  15493. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15494. };
  15495. Engine.prototype.endTransformFeedback = function () {
  15496. this._gl.endTransformFeedback();
  15497. };
  15498. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15499. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15500. };
  15501. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15502. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15503. };
  15504. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15505. var _this = this;
  15506. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15507. this._activeRequests.push(request);
  15508. request.onCompleteObservable.add(function (request) {
  15509. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15510. });
  15511. return request;
  15512. };
  15513. /** @ignore */
  15514. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15515. var _this = this;
  15516. return new Promise(function (resolve, reject) {
  15517. _this._loadFile(url, function (data) {
  15518. resolve(data);
  15519. }, undefined, database, useArrayBuffer, function (request, exception) {
  15520. reject(exception);
  15521. });
  15522. });
  15523. };
  15524. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15525. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15526. var onload = function (data) {
  15527. loadedFiles[index] = data;
  15528. loadedFiles._internalCount++;
  15529. if (loadedFiles._internalCount === 6) {
  15530. onfinish(loadedFiles);
  15531. }
  15532. };
  15533. var onerror = function (request, exception) {
  15534. if (onErrorCallBack && request) {
  15535. onErrorCallBack(request.status + " " + request.statusText, exception);
  15536. }
  15537. };
  15538. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15539. };
  15540. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15541. if (onError === void 0) { onError = null; }
  15542. var loadedFiles = [];
  15543. loadedFiles._internalCount = 0;
  15544. for (var index = 0; index < 6; index++) {
  15545. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15546. }
  15547. };
  15548. // Statics
  15549. Engine.isSupported = function () {
  15550. try {
  15551. var tempcanvas = document.createElement("canvas");
  15552. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15553. return gl != null && !!window.WebGLRenderingContext;
  15554. }
  15555. catch (e) {
  15556. return false;
  15557. }
  15558. };
  15559. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15560. Engine.ExceptionList = [
  15561. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15562. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15563. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15564. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15565. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15566. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15567. ];
  15568. Engine.Instances = new Array();
  15569. // Const statics
  15570. Engine._ALPHA_DISABLE = 0;
  15571. Engine._ALPHA_ADD = 1;
  15572. Engine._ALPHA_COMBINE = 2;
  15573. Engine._ALPHA_SUBTRACT = 3;
  15574. Engine._ALPHA_MULTIPLY = 4;
  15575. Engine._ALPHA_MAXIMIZED = 5;
  15576. Engine._ALPHA_ONEONE = 6;
  15577. Engine._ALPHA_PREMULTIPLIED = 7;
  15578. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15579. Engine._ALPHA_INTERPOLATE = 9;
  15580. Engine._ALPHA_SCREENMODE = 10;
  15581. Engine._DELAYLOADSTATE_NONE = 0;
  15582. Engine._DELAYLOADSTATE_LOADED = 1;
  15583. Engine._DELAYLOADSTATE_LOADING = 2;
  15584. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15585. Engine._TEXTUREFORMAT_ALPHA = 0;
  15586. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15587. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15588. Engine._TEXTUREFORMAT_RGB = 4;
  15589. Engine._TEXTUREFORMAT_RGBA = 5;
  15590. Engine._TEXTUREFORMAT_R32F = 6;
  15591. Engine._TEXTUREFORMAT_RG32F = 7;
  15592. Engine._TEXTUREFORMAT_RGB32F = 8;
  15593. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15594. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15595. Engine._TEXTURETYPE_FLOAT = 1;
  15596. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15597. // Depht or Stencil test Constants.
  15598. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15599. 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.
  15600. 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.
  15601. 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.
  15602. 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.
  15603. 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.
  15604. 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.
  15605. 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.
  15606. // Stencil Actions Constants.
  15607. Engine._KEEP = 0x1E00;
  15608. Engine._REPLACE = 0x1E01;
  15609. Engine._INCR = 0x1E02;
  15610. Engine._DECR = 0x1E03;
  15611. Engine._INVERT = 0x150A;
  15612. Engine._INCR_WRAP = 0x8507;
  15613. Engine._DECR_WRAP = 0x8508;
  15614. // Texture rescaling mode
  15615. Engine._SCALEMODE_FLOOR = 1;
  15616. Engine._SCALEMODE_NEAREST = 2;
  15617. Engine._SCALEMODE_CEILING = 3;
  15618. // Updatable statics so stick with vars here
  15619. Engine.CollisionsEpsilon = 0.001;
  15620. Engine.CodeRepository = "src/";
  15621. Engine.ShadersRepository = "src/Shaders/";
  15622. return Engine;
  15623. }());
  15624. BABYLON.Engine = Engine;
  15625. })(BABYLON || (BABYLON = {}));
  15626. //# sourceMappingURL=babylon.engine.js.map
  15627. "use strict";
  15628. var BABYLON;
  15629. (function (BABYLON) {
  15630. /**
  15631. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15632. */
  15633. var Node = /** @class */ (function () {
  15634. /**
  15635. * Creates a new Node
  15636. * @param {string} name - the name and id to be given to this node
  15637. * @param {BABYLON.Scene} the scene this node will be added to
  15638. */
  15639. function Node(name, scene) {
  15640. if (scene === void 0) { scene = null; }
  15641. /**
  15642. * Gets or sets a string used to store user defined state for the node
  15643. */
  15644. this.state = "";
  15645. /**
  15646. * Gets or sets an object used to store user defined information for the node
  15647. */
  15648. this.metadata = null;
  15649. /**
  15650. * Gets or sets a boolean used to define if the node must be serialized
  15651. */
  15652. this.doNotSerialize = false;
  15653. /** @ignore */
  15654. this._isDisposed = false;
  15655. /**
  15656. * Gets a list of {BABYLON.Animation} associated with the node
  15657. */
  15658. this.animations = new Array();
  15659. this._ranges = {};
  15660. this._isEnabled = true;
  15661. this._isReady = true;
  15662. /** @ignore */
  15663. this._currentRenderId = -1;
  15664. this._parentRenderId = -1;
  15665. this._childRenderId = -1;
  15666. this._animationPropertiesOverride = null;
  15667. /**
  15668. * An event triggered when the mesh is disposed
  15669. * @type {BABYLON.Observable}
  15670. */
  15671. this.onDisposeObservable = new BABYLON.Observable();
  15672. // Behaviors
  15673. this._behaviors = new Array();
  15674. this.name = name;
  15675. this.id = name;
  15676. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15677. this.uniqueId = this._scene.getUniqueId();
  15678. this._initCache();
  15679. }
  15680. /**
  15681. * Gets a boolean indicating if the node has been disposed
  15682. * @returns true if the node was disposed
  15683. */
  15684. Node.prototype.isDisposed = function () {
  15685. return this._isDisposed;
  15686. };
  15687. Object.defineProperty(Node.prototype, "parent", {
  15688. get: function () {
  15689. return this._parentNode;
  15690. },
  15691. /**
  15692. * Gets or sets the parent of the node
  15693. */
  15694. set: function (parent) {
  15695. if (this._parentNode === parent) {
  15696. return;
  15697. }
  15698. // Remove self from list of children of parent
  15699. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15700. var index = this._parentNode._children.indexOf(this);
  15701. if (index !== -1) {
  15702. this._parentNode._children.splice(index, 1);
  15703. }
  15704. }
  15705. // Store new parent
  15706. this._parentNode = parent;
  15707. // Add as child to new parent
  15708. if (this._parentNode) {
  15709. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15710. this._parentNode._children = new Array();
  15711. }
  15712. this._parentNode._children.push(this);
  15713. }
  15714. },
  15715. enumerable: true,
  15716. configurable: true
  15717. });
  15718. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15719. /**
  15720. * Gets or sets the animation properties override
  15721. */
  15722. get: function () {
  15723. return this._animationPropertiesOverride;
  15724. },
  15725. set: function (value) {
  15726. this._animationPropertiesOverride = value;
  15727. },
  15728. enumerable: true,
  15729. configurable: true
  15730. });
  15731. /**
  15732. * Gets a string idenfifying the name of the class
  15733. * @returns "Node" string
  15734. */
  15735. Node.prototype.getClassName = function () {
  15736. return "Node";
  15737. };
  15738. Object.defineProperty(Node.prototype, "onDispose", {
  15739. /**
  15740. * Sets a callback that will be raised when the node will be disposed
  15741. */
  15742. set: function (callback) {
  15743. if (this._onDisposeObserver) {
  15744. this.onDisposeObservable.remove(this._onDisposeObserver);
  15745. }
  15746. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15747. },
  15748. enumerable: true,
  15749. configurable: true
  15750. });
  15751. /**
  15752. * Gets the scene of the node
  15753. * @returns a {BABYLON.Scene}
  15754. */
  15755. Node.prototype.getScene = function () {
  15756. return this._scene;
  15757. };
  15758. /**
  15759. * Gets the engine of the node
  15760. * @returns a {BABYLON.Engine}
  15761. */
  15762. Node.prototype.getEngine = function () {
  15763. return this._scene.getEngine();
  15764. };
  15765. /**
  15766. * Attach a behavior to the node
  15767. * @see http://doc.babylonjs.com/features/behaviour
  15768. * @param behavior defines the behavior to attach
  15769. * @returns the current Node
  15770. */
  15771. Node.prototype.addBehavior = function (behavior) {
  15772. var _this = this;
  15773. var index = this._behaviors.indexOf(behavior);
  15774. if (index !== -1) {
  15775. return this;
  15776. }
  15777. behavior.init();
  15778. if (this._scene.isLoading) {
  15779. // We defer the attach when the scene will be loaded
  15780. var observer = this._scene.onDataLoadedObservable.add(function () {
  15781. behavior.attach(_this);
  15782. setTimeout(function () {
  15783. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15784. _this._scene.onDataLoadedObservable.remove(observer);
  15785. }, 0);
  15786. });
  15787. }
  15788. else {
  15789. behavior.attach(this);
  15790. }
  15791. this._behaviors.push(behavior);
  15792. return this;
  15793. };
  15794. /**
  15795. * Remove an attached behavior
  15796. * @see http://doc.babylonjs.com/features/behaviour
  15797. * @param behavior defines the behavior to attach
  15798. * @returns the current Node
  15799. */
  15800. Node.prototype.removeBehavior = function (behavior) {
  15801. var index = this._behaviors.indexOf(behavior);
  15802. if (index === -1) {
  15803. return this;
  15804. }
  15805. this._behaviors[index].detach();
  15806. this._behaviors.splice(index, 1);
  15807. return this;
  15808. };
  15809. Object.defineProperty(Node.prototype, "behaviors", {
  15810. /**
  15811. * Gets the list of attached behaviors
  15812. * @see http://doc.babylonjs.com/features/behaviour
  15813. */
  15814. get: function () {
  15815. return this._behaviors;
  15816. },
  15817. enumerable: true,
  15818. configurable: true
  15819. });
  15820. /**
  15821. * Gets an attached behavior by name
  15822. * @param name defines the name of the behavior to look for
  15823. * @see http://doc.babylonjs.com/features/behaviour
  15824. * @returns null if behavior was not found else the requested behavior
  15825. */
  15826. Node.prototype.getBehaviorByName = function (name) {
  15827. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15828. var behavior = _a[_i];
  15829. if (behavior.name === name) {
  15830. return behavior;
  15831. }
  15832. }
  15833. return null;
  15834. };
  15835. /**
  15836. * Returns the world matrix of the node
  15837. * @returns a matrix containing the node's world matrix
  15838. */
  15839. Node.prototype.getWorldMatrix = function () {
  15840. return BABYLON.Matrix.Identity();
  15841. };
  15842. // override it in derived class if you add new variables to the cache
  15843. // and call the parent class method
  15844. /** @ignore */
  15845. Node.prototype._initCache = function () {
  15846. this._cache = {};
  15847. this._cache.parent = undefined;
  15848. };
  15849. /** @ignore */
  15850. Node.prototype.updateCache = function (force) {
  15851. if (!force && this.isSynchronized())
  15852. return;
  15853. this._cache.parent = this.parent;
  15854. this._updateCache();
  15855. };
  15856. // override it in derived class if you add new variables to the cache
  15857. // and call the parent class method if !ignoreParentClass
  15858. /** @ignore */
  15859. Node.prototype._updateCache = function (ignoreParentClass) {
  15860. };
  15861. // override it in derived class if you add new variables to the cache
  15862. /** @ignore */
  15863. Node.prototype._isSynchronized = function () {
  15864. return true;
  15865. };
  15866. /** @ignore */
  15867. Node.prototype._markSyncedWithParent = function () {
  15868. if (this.parent) {
  15869. this._parentRenderId = this.parent._childRenderId;
  15870. }
  15871. };
  15872. /** @ignore */
  15873. Node.prototype.isSynchronizedWithParent = function () {
  15874. if (!this.parent) {
  15875. return true;
  15876. }
  15877. if (this._parentRenderId !== this.parent._childRenderId) {
  15878. return false;
  15879. }
  15880. return this.parent.isSynchronized();
  15881. };
  15882. /** @ignore */
  15883. Node.prototype.isSynchronized = function (updateCache) {
  15884. var check = this.hasNewParent();
  15885. check = check || !this.isSynchronizedWithParent();
  15886. check = check || !this._isSynchronized();
  15887. if (updateCache)
  15888. this.updateCache(true);
  15889. return !check;
  15890. };
  15891. /** @ignore */
  15892. Node.prototype.hasNewParent = function (update) {
  15893. if (this._cache.parent === this.parent)
  15894. return false;
  15895. if (update)
  15896. this._cache.parent = this.parent;
  15897. return true;
  15898. };
  15899. /**
  15900. * Is this node ready to be used/rendered
  15901. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15902. * @return true if the node is ready
  15903. */
  15904. Node.prototype.isReady = function (completeCheck) {
  15905. if (completeCheck === void 0) { completeCheck = false; }
  15906. return this._isReady;
  15907. };
  15908. /**
  15909. * Is this node enabled?
  15910. * 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
  15911. * @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
  15912. * @return whether this node (and its parent) is enabled
  15913. * @see setEnabled
  15914. */
  15915. Node.prototype.isEnabled = function (checkAncestors) {
  15916. if (checkAncestors === void 0) { checkAncestors = true; }
  15917. if (checkAncestors === false) {
  15918. return this._isEnabled;
  15919. }
  15920. if (this._isEnabled === false) {
  15921. return false;
  15922. }
  15923. if (this.parent !== undefined && this.parent !== null) {
  15924. return this.parent.isEnabled(checkAncestors);
  15925. }
  15926. return true;
  15927. };
  15928. /**
  15929. * Set the enabled state of this node
  15930. * @param value defines the new enabled state
  15931. * @see isEnabled
  15932. */
  15933. Node.prototype.setEnabled = function (value) {
  15934. this._isEnabled = value;
  15935. };
  15936. /**
  15937. * Is this node a descendant of the given node?
  15938. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15939. * @param ancestor defines the parent node to inspect
  15940. * @see parent
  15941. * @returns a boolean indicating if this node is a descendant of the given node
  15942. */
  15943. Node.prototype.isDescendantOf = function (ancestor) {
  15944. if (this.parent) {
  15945. if (this.parent === ancestor) {
  15946. return true;
  15947. }
  15948. return this.parent.isDescendantOf(ancestor);
  15949. }
  15950. return false;
  15951. };
  15952. /** @ignore */
  15953. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15954. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15955. if (!this._children) {
  15956. return;
  15957. }
  15958. for (var index = 0; index < this._children.length; index++) {
  15959. var item = this._children[index];
  15960. if (!predicate || predicate(item)) {
  15961. results.push(item);
  15962. }
  15963. if (!directDescendantsOnly) {
  15964. item._getDescendants(results, false, predicate);
  15965. }
  15966. }
  15967. };
  15968. /**
  15969. * Will return all nodes that have this node as ascendant
  15970. * @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
  15971. * @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
  15972. * @return all children nodes of all types
  15973. */
  15974. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15975. var results = new Array();
  15976. this._getDescendants(results, directDescendantsOnly, predicate);
  15977. return results;
  15978. };
  15979. /**
  15980. * Get all child-meshes of this node
  15981. * @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
  15982. * @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
  15983. * @returns an array of {BABYLON.AbstractMesh}
  15984. */
  15985. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15986. var results = [];
  15987. this._getDescendants(results, directDescendantsOnly, function (node) {
  15988. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15989. });
  15990. return results;
  15991. };
  15992. /**
  15993. * Get all child-transformNodes of this node
  15994. * @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
  15995. * @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
  15996. * @returns an array of {BABYLON.TransformNode}
  15997. */
  15998. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15999. var results = [];
  16000. this._getDescendants(results, directDescendantsOnly, function (node) {
  16001. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16002. });
  16003. return results;
  16004. };
  16005. /**
  16006. * Get all direct children of this node
  16007. * @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
  16008. * @returns an array of {BABYLON.Node}
  16009. */
  16010. Node.prototype.getChildren = function (predicate) {
  16011. return this.getDescendants(true, predicate);
  16012. };
  16013. /** @ignore */
  16014. Node.prototype._setReady = function (state) {
  16015. if (state === this._isReady) {
  16016. return;
  16017. }
  16018. if (!state) {
  16019. this._isReady = false;
  16020. return;
  16021. }
  16022. if (this.onReady) {
  16023. this.onReady(this);
  16024. }
  16025. this._isReady = true;
  16026. };
  16027. /**
  16028. * Get an animation by name
  16029. * @param name defines the name of the animation to look for
  16030. * @returns null if not found else the requested animation
  16031. */
  16032. Node.prototype.getAnimationByName = function (name) {
  16033. for (var i = 0; i < this.animations.length; i++) {
  16034. var animation = this.animations[i];
  16035. if (animation.name === name) {
  16036. return animation;
  16037. }
  16038. }
  16039. return null;
  16040. };
  16041. /**
  16042. * Creates an animation range for this node
  16043. * @param name defines the name of the range
  16044. * @param from defines the starting key
  16045. * @param to defines the end key
  16046. */
  16047. Node.prototype.createAnimationRange = function (name, from, to) {
  16048. // check name not already in use
  16049. if (!this._ranges[name]) {
  16050. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16051. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16052. if (this.animations[i]) {
  16053. this.animations[i].createRange(name, from, to);
  16054. }
  16055. }
  16056. }
  16057. };
  16058. /**
  16059. * Delete a specific animation range
  16060. * @param name defines the name of the range to delete
  16061. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16062. */
  16063. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16064. if (deleteFrames === void 0) { deleteFrames = true; }
  16065. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16066. if (this.animations[i]) {
  16067. this.animations[i].deleteRange(name, deleteFrames);
  16068. }
  16069. }
  16070. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16071. };
  16072. /**
  16073. * Get an animation range by name
  16074. * @param name defines the name of the animation range to look for
  16075. * @returns null if not found else the requested animation range
  16076. */
  16077. Node.prototype.getAnimationRange = function (name) {
  16078. return this._ranges[name];
  16079. };
  16080. /**
  16081. * Will start the animation sequence
  16082. * @param name defines the range frames for animation sequence
  16083. * @param loop defines if the animation should loop (false by default)
  16084. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16085. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16086. * @returns the object created for this animation. If range does not exist, it will return null
  16087. */
  16088. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16089. var range = this.getAnimationRange(name);
  16090. if (!range) {
  16091. return null;
  16092. }
  16093. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16094. };
  16095. /**
  16096. * Serialize animation ranges into a JSON compatible object
  16097. * @returns serialization object
  16098. */
  16099. Node.prototype.serializeAnimationRanges = function () {
  16100. var serializationRanges = [];
  16101. for (var name in this._ranges) {
  16102. var localRange = this._ranges[name];
  16103. if (!localRange) {
  16104. continue;
  16105. }
  16106. var range = {};
  16107. range.name = name;
  16108. range.from = localRange.from;
  16109. range.to = localRange.to;
  16110. serializationRanges.push(range);
  16111. }
  16112. return serializationRanges;
  16113. };
  16114. /**
  16115. * Computes the world matrix of the node
  16116. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16117. * @returns the world matrix
  16118. */
  16119. Node.prototype.computeWorldMatrix = function (force) {
  16120. return BABYLON.Matrix.Identity();
  16121. };
  16122. /**
  16123. * Releases resources associated with this node.
  16124. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16125. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16126. */
  16127. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16128. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16129. if (!doNotRecurse) {
  16130. var nodes = this.getDescendants(true);
  16131. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16132. var node = nodes_1[_i];
  16133. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16134. }
  16135. }
  16136. else {
  16137. var transformNodes = this.getChildTransformNodes(true);
  16138. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16139. var transformNode = transformNodes_1[_a];
  16140. transformNode.parent = null;
  16141. transformNode.computeWorldMatrix(true);
  16142. }
  16143. }
  16144. this.parent = null;
  16145. // Callback
  16146. this.onDisposeObservable.notifyObservers(this);
  16147. this.onDisposeObservable.clear();
  16148. // Behaviors
  16149. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16150. var behavior = _c[_b];
  16151. behavior.detach();
  16152. }
  16153. this._behaviors = [];
  16154. this._isDisposed = true;
  16155. };
  16156. /**
  16157. * Parse animation range data from a serialization object and store them into a given node
  16158. * @param node defines where to store the animation ranges
  16159. * @param parsedNode defines the serialization object to read data from
  16160. * @param scene defines the hosting scene
  16161. */
  16162. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16163. if (parsedNode.ranges) {
  16164. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16165. var data = parsedNode.ranges[index];
  16166. node.createAnimationRange(data.name, data.from, data.to);
  16167. }
  16168. }
  16169. };
  16170. __decorate([
  16171. BABYLON.serialize()
  16172. ], Node.prototype, "name", void 0);
  16173. __decorate([
  16174. BABYLON.serialize()
  16175. ], Node.prototype, "id", void 0);
  16176. __decorate([
  16177. BABYLON.serialize()
  16178. ], Node.prototype, "uniqueId", void 0);
  16179. __decorate([
  16180. BABYLON.serialize()
  16181. ], Node.prototype, "state", void 0);
  16182. __decorate([
  16183. BABYLON.serialize()
  16184. ], Node.prototype, "metadata", void 0);
  16185. return Node;
  16186. }());
  16187. BABYLON.Node = Node;
  16188. })(BABYLON || (BABYLON = {}));
  16189. //# sourceMappingURL=babylon.node.js.map
  16190. "use strict";
  16191. var BABYLON;
  16192. (function (BABYLON) {
  16193. var BoundingSphere = /** @class */ (function () {
  16194. function BoundingSphere(minimum, maximum) {
  16195. this.minimum = minimum;
  16196. this.maximum = maximum;
  16197. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16198. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16199. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16200. this.radius = distance * 0.5;
  16201. this.centerWorld = BABYLON.Vector3.Zero();
  16202. this._update(BABYLON.Matrix.Identity());
  16203. }
  16204. // Methods
  16205. BoundingSphere.prototype._update = function (world) {
  16206. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16207. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16208. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16209. };
  16210. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16211. for (var i = 0; i < 6; i++) {
  16212. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16213. return false;
  16214. }
  16215. return true;
  16216. };
  16217. BoundingSphere.prototype.intersectsPoint = function (point) {
  16218. var x = this.centerWorld.x - point.x;
  16219. var y = this.centerWorld.y - point.y;
  16220. var z = this.centerWorld.z - point.z;
  16221. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16222. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16223. return false;
  16224. return true;
  16225. };
  16226. // Statics
  16227. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16228. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16229. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16230. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16231. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16232. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16233. return false;
  16234. return true;
  16235. };
  16236. return BoundingSphere;
  16237. }());
  16238. BABYLON.BoundingSphere = BoundingSphere;
  16239. })(BABYLON || (BABYLON = {}));
  16240. //# sourceMappingURL=babylon.boundingSphere.js.map
  16241. "use strict";
  16242. var BABYLON;
  16243. (function (BABYLON) {
  16244. var BoundingBox = /** @class */ (function () {
  16245. function BoundingBox(minimum, maximum) {
  16246. this.minimum = minimum;
  16247. this.maximum = maximum;
  16248. this.vectors = new Array();
  16249. this.vectorsWorld = new Array();
  16250. // Bounding vectors
  16251. this.vectors.push(this.minimum.clone());
  16252. this.vectors.push(this.maximum.clone());
  16253. this.vectors.push(this.minimum.clone());
  16254. this.vectors[2].x = this.maximum.x;
  16255. this.vectors.push(this.minimum.clone());
  16256. this.vectors[3].y = this.maximum.y;
  16257. this.vectors.push(this.minimum.clone());
  16258. this.vectors[4].z = this.maximum.z;
  16259. this.vectors.push(this.maximum.clone());
  16260. this.vectors[5].z = this.minimum.z;
  16261. this.vectors.push(this.maximum.clone());
  16262. this.vectors[6].x = this.minimum.x;
  16263. this.vectors.push(this.maximum.clone());
  16264. this.vectors[7].y = this.minimum.y;
  16265. // OBB
  16266. this.center = this.maximum.add(this.minimum).scale(0.5);
  16267. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16268. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16269. // World
  16270. for (var index = 0; index < this.vectors.length; index++) {
  16271. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16272. }
  16273. this.minimumWorld = BABYLON.Vector3.Zero();
  16274. this.maximumWorld = BABYLON.Vector3.Zero();
  16275. this.centerWorld = BABYLON.Vector3.Zero();
  16276. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16277. this._update(BABYLON.Matrix.Identity());
  16278. }
  16279. // Methods
  16280. BoundingBox.prototype.getWorldMatrix = function () {
  16281. return this._worldMatrix;
  16282. };
  16283. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16284. this._worldMatrix.copyFrom(matrix);
  16285. return this;
  16286. };
  16287. BoundingBox.prototype._update = function (world) {
  16288. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16289. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16290. for (var index = 0; index < this.vectors.length; index++) {
  16291. var v = this.vectorsWorld[index];
  16292. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16293. if (v.x < this.minimumWorld.x)
  16294. this.minimumWorld.x = v.x;
  16295. if (v.y < this.minimumWorld.y)
  16296. this.minimumWorld.y = v.y;
  16297. if (v.z < this.minimumWorld.z)
  16298. this.minimumWorld.z = v.z;
  16299. if (v.x > this.maximumWorld.x)
  16300. this.maximumWorld.x = v.x;
  16301. if (v.y > this.maximumWorld.y)
  16302. this.maximumWorld.y = v.y;
  16303. if (v.z > this.maximumWorld.z)
  16304. this.maximumWorld.z = v.z;
  16305. }
  16306. // Extend
  16307. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16308. this.extendSizeWorld.scaleInPlace(0.5);
  16309. // OBB
  16310. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16311. this.centerWorld.scaleInPlace(0.5);
  16312. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16313. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16314. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16315. this._worldMatrix = world;
  16316. };
  16317. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16318. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16319. };
  16320. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16321. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16322. };
  16323. BoundingBox.prototype.intersectsPoint = function (point) {
  16324. var delta = -BABYLON.Epsilon;
  16325. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16326. return false;
  16327. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16328. return false;
  16329. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16330. return false;
  16331. return true;
  16332. };
  16333. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16334. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16335. };
  16336. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16337. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16338. return false;
  16339. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16340. return false;
  16341. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16342. return false;
  16343. return true;
  16344. };
  16345. // Statics
  16346. BoundingBox.Intersects = function (box0, box1) {
  16347. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16348. return false;
  16349. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16350. return false;
  16351. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16352. return false;
  16353. return true;
  16354. };
  16355. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16356. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16357. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16358. return (num <= (sphereRadius * sphereRadius));
  16359. };
  16360. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16361. for (var p = 0; p < 6; p++) {
  16362. for (var i = 0; i < 8; i++) {
  16363. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16364. return false;
  16365. }
  16366. }
  16367. }
  16368. return true;
  16369. };
  16370. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16371. for (var p = 0; p < 6; p++) {
  16372. var inCount = 8;
  16373. for (var i = 0; i < 8; i++) {
  16374. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16375. --inCount;
  16376. }
  16377. else {
  16378. break;
  16379. }
  16380. }
  16381. if (inCount === 0)
  16382. return false;
  16383. }
  16384. return true;
  16385. };
  16386. return BoundingBox;
  16387. }());
  16388. BABYLON.BoundingBox = BoundingBox;
  16389. })(BABYLON || (BABYLON = {}));
  16390. //# sourceMappingURL=babylon.boundingBox.js.map
  16391. "use strict";
  16392. var BABYLON;
  16393. (function (BABYLON) {
  16394. var computeBoxExtents = function (axis, box) {
  16395. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16396. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16397. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16398. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16399. var r = r0 + r1 + r2;
  16400. return {
  16401. min: p - r,
  16402. max: p + r
  16403. };
  16404. };
  16405. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16406. var axisOverlap = function (axis, box0, box1) {
  16407. var result0 = computeBoxExtents(axis, box0);
  16408. var result1 = computeBoxExtents(axis, box1);
  16409. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16410. };
  16411. var BoundingInfo = /** @class */ (function () {
  16412. function BoundingInfo(minimum, maximum) {
  16413. this.minimum = minimum;
  16414. this.maximum = maximum;
  16415. this._isLocked = false;
  16416. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16417. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16418. }
  16419. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16420. get: function () {
  16421. return this._isLocked;
  16422. },
  16423. set: function (value) {
  16424. this._isLocked = value;
  16425. },
  16426. enumerable: true,
  16427. configurable: true
  16428. });
  16429. // Methods
  16430. BoundingInfo.prototype.update = function (world) {
  16431. if (this._isLocked) {
  16432. return;
  16433. }
  16434. this.boundingBox._update(world);
  16435. this.boundingSphere._update(world);
  16436. };
  16437. /**
  16438. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16439. * @param center New center of the bounding info
  16440. * @param extend New extend of the bounding info
  16441. */
  16442. BoundingInfo.prototype.centerOn = function (center, extend) {
  16443. this.minimum = center.subtract(extend);
  16444. this.maximum = center.add(extend);
  16445. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16446. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16447. return this;
  16448. };
  16449. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16450. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16451. return false;
  16452. return this.boundingBox.isInFrustum(frustumPlanes);
  16453. };
  16454. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16455. /**
  16456. * Gets the world distance between the min and max points of the bounding box
  16457. */
  16458. get: function () {
  16459. var boundingBox = this.boundingBox;
  16460. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16461. return size.length();
  16462. },
  16463. enumerable: true,
  16464. configurable: true
  16465. });
  16466. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16467. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16468. };
  16469. BoundingInfo.prototype._checkCollision = function (collider) {
  16470. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16471. };
  16472. BoundingInfo.prototype.intersectsPoint = function (point) {
  16473. if (!this.boundingSphere.centerWorld) {
  16474. return false;
  16475. }
  16476. if (!this.boundingSphere.intersectsPoint(point)) {
  16477. return false;
  16478. }
  16479. if (!this.boundingBox.intersectsPoint(point)) {
  16480. return false;
  16481. }
  16482. return true;
  16483. };
  16484. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16485. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16486. return false;
  16487. }
  16488. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16489. return false;
  16490. }
  16491. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16492. return false;
  16493. }
  16494. if (!precise) {
  16495. return true;
  16496. }
  16497. var box0 = this.boundingBox;
  16498. var box1 = boundingInfo.boundingBox;
  16499. if (!axisOverlap(box0.directions[0], box0, box1))
  16500. return false;
  16501. if (!axisOverlap(box0.directions[1], box0, box1))
  16502. return false;
  16503. if (!axisOverlap(box0.directions[2], box0, box1))
  16504. return false;
  16505. if (!axisOverlap(box1.directions[0], box0, box1))
  16506. return false;
  16507. if (!axisOverlap(box1.directions[1], box0, box1))
  16508. return false;
  16509. if (!axisOverlap(box1.directions[2], box0, box1))
  16510. return false;
  16511. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16512. return false;
  16513. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16514. return false;
  16515. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16516. return false;
  16517. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16518. return false;
  16519. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16520. return false;
  16521. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16522. return false;
  16523. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16524. return false;
  16525. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16526. return false;
  16527. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16528. return false;
  16529. return true;
  16530. };
  16531. return BoundingInfo;
  16532. }());
  16533. BABYLON.BoundingInfo = BoundingInfo;
  16534. })(BABYLON || (BABYLON = {}));
  16535. //# sourceMappingURL=babylon.boundingInfo.js.map
  16536. "use strict";
  16537. var BABYLON;
  16538. (function (BABYLON) {
  16539. var TransformNode = /** @class */ (function (_super) {
  16540. __extends(TransformNode, _super);
  16541. function TransformNode(name, scene, isPure) {
  16542. if (scene === void 0) { scene = null; }
  16543. if (isPure === void 0) { isPure = true; }
  16544. var _this = _super.call(this, name, scene) || this;
  16545. _this._forward = new BABYLON.Vector3(0, 0, 1);
  16546. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  16547. _this._up = new BABYLON.Vector3(0, 1, 0);
  16548. _this._right = new BABYLON.Vector3(1, 0, 0);
  16549. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  16550. // Properties
  16551. _this._rotation = BABYLON.Vector3.Zero();
  16552. _this._scaling = BABYLON.Vector3.One();
  16553. _this._isDirty = false;
  16554. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  16555. _this.scalingDeterminant = 1;
  16556. _this.infiniteDistance = false;
  16557. _this.position = BABYLON.Vector3.Zero();
  16558. _this._localWorld = BABYLON.Matrix.Zero();
  16559. _this._worldMatrix = BABYLON.Matrix.Zero();
  16560. _this._worldMatrixDeterminant = 0;
  16561. _this._absolutePosition = BABYLON.Vector3.Zero();
  16562. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16563. _this._postMultiplyPivotMatrix = false;
  16564. _this._isWorldMatrixFrozen = false;
  16565. /**
  16566. * An event triggered after the world matrix is updated
  16567. * @type {BABYLON.Observable}
  16568. */
  16569. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16570. _this._nonUniformScaling = false;
  16571. if (isPure) {
  16572. _this.getScene().addTransformNode(_this);
  16573. }
  16574. return _this;
  16575. }
  16576. /**
  16577. * Gets a string idenfifying the name of the class
  16578. * @returns "TransformNode" string
  16579. */
  16580. TransformNode.prototype.getClassName = function () {
  16581. return "TransformNode";
  16582. };
  16583. Object.defineProperty(TransformNode.prototype, "rotation", {
  16584. /**
  16585. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16586. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16587. * Default : (0.0, 0.0, 0.0)
  16588. */
  16589. get: function () {
  16590. return this._rotation;
  16591. },
  16592. set: function (newRotation) {
  16593. this._rotation = newRotation;
  16594. },
  16595. enumerable: true,
  16596. configurable: true
  16597. });
  16598. Object.defineProperty(TransformNode.prototype, "scaling", {
  16599. /**
  16600. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16601. * Default : (1.0, 1.0, 1.0)
  16602. */
  16603. get: function () {
  16604. return this._scaling;
  16605. },
  16606. /**
  16607. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16608. * Default : (1.0, 1.0, 1.0)
  16609. */
  16610. set: function (newScaling) {
  16611. this._scaling = newScaling;
  16612. },
  16613. enumerable: true,
  16614. configurable: true
  16615. });
  16616. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16617. /**
  16618. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16619. * It's null by default.
  16620. * 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)
  16621. */
  16622. get: function () {
  16623. return this._rotationQuaternion;
  16624. },
  16625. set: function (quaternion) {
  16626. this._rotationQuaternion = quaternion;
  16627. //reset the rotation vector.
  16628. if (quaternion && this.rotation.length()) {
  16629. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16630. }
  16631. },
  16632. enumerable: true,
  16633. configurable: true
  16634. });
  16635. Object.defineProperty(TransformNode.prototype, "forward", {
  16636. /**
  16637. * The forward direction of that transform in world space.
  16638. */
  16639. get: function () {
  16640. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  16641. },
  16642. enumerable: true,
  16643. configurable: true
  16644. });
  16645. Object.defineProperty(TransformNode.prototype, "up", {
  16646. /**
  16647. * The up direction of that transform in world space.
  16648. */
  16649. get: function () {
  16650. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  16651. },
  16652. enumerable: true,
  16653. configurable: true
  16654. });
  16655. Object.defineProperty(TransformNode.prototype, "right", {
  16656. /**
  16657. * The right direction of that transform in world space.
  16658. */
  16659. get: function () {
  16660. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  16661. },
  16662. enumerable: true,
  16663. configurable: true
  16664. });
  16665. /**
  16666. * Returns the latest update of the World matrix
  16667. * Returns a Matrix.
  16668. */
  16669. TransformNode.prototype.getWorldMatrix = function () {
  16670. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16671. this.computeWorldMatrix();
  16672. }
  16673. return this._worldMatrix;
  16674. };
  16675. /**
  16676. * Returns the latest update of the World matrix determinant.
  16677. */
  16678. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16679. return this._worldMatrixDeterminant;
  16680. };
  16681. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16682. /**
  16683. * Returns directly the latest state of the mesh World matrix.
  16684. * A Matrix is returned.
  16685. */
  16686. get: function () {
  16687. return this._worldMatrix;
  16688. },
  16689. enumerable: true,
  16690. configurable: true
  16691. });
  16692. /**
  16693. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16694. * Returns the TransformNode.
  16695. */
  16696. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16697. this._poseMatrix.copyFrom(matrix);
  16698. return this;
  16699. };
  16700. /**
  16701. * Returns the mesh Pose matrix.
  16702. * Returned object : Matrix
  16703. */
  16704. TransformNode.prototype.getPoseMatrix = function () {
  16705. return this._poseMatrix;
  16706. };
  16707. TransformNode.prototype._isSynchronized = function () {
  16708. if (this._isDirty) {
  16709. return false;
  16710. }
  16711. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  16712. return false;
  16713. if (this._cache.pivotMatrixUpdated) {
  16714. return false;
  16715. }
  16716. if (this.infiniteDistance) {
  16717. return false;
  16718. }
  16719. if (!this._cache.position.equals(this.position))
  16720. return false;
  16721. if (this.rotationQuaternion) {
  16722. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16723. return false;
  16724. }
  16725. if (!this._cache.rotation.equals(this.rotation))
  16726. return false;
  16727. if (!this._cache.scaling.equals(this.scaling))
  16728. return false;
  16729. return true;
  16730. };
  16731. TransformNode.prototype._initCache = function () {
  16732. _super.prototype._initCache.call(this);
  16733. this._cache.localMatrixUpdated = false;
  16734. this._cache.position = BABYLON.Vector3.Zero();
  16735. this._cache.scaling = BABYLON.Vector3.Zero();
  16736. this._cache.rotation = BABYLON.Vector3.Zero();
  16737. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16738. this._cache.billboardMode = -1;
  16739. };
  16740. TransformNode.prototype.markAsDirty = function (property) {
  16741. if (property === "rotation") {
  16742. this.rotationQuaternion = null;
  16743. }
  16744. this._currentRenderId = Number.MAX_VALUE;
  16745. this._isDirty = true;
  16746. return this;
  16747. };
  16748. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16749. /**
  16750. * Returns the current mesh absolute position.
  16751. * Retuns a Vector3.
  16752. */
  16753. get: function () {
  16754. return this._absolutePosition;
  16755. },
  16756. enumerable: true,
  16757. configurable: true
  16758. });
  16759. /**
  16760. * Sets a new matrix to apply before all other transformation
  16761. * @param matrix defines the transform matrix
  16762. * @returns the current TransformNode
  16763. */
  16764. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16765. return this.setPivotMatrix(matrix, false);
  16766. };
  16767. /**
  16768. * Sets a new pivot matrix to the current node
  16769. * @param matrix defines the new pivot matrix to use
  16770. * @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
  16771. * @returns the current TransformNode
  16772. */
  16773. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16774. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16775. this._pivotMatrix = matrix.clone();
  16776. this._cache.pivotMatrixUpdated = true;
  16777. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16778. if (this._postMultiplyPivotMatrix) {
  16779. if (!this._pivotMatrixInverse) {
  16780. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16781. }
  16782. else {
  16783. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16784. }
  16785. }
  16786. return this;
  16787. };
  16788. /**
  16789. * Returns the mesh pivot matrix.
  16790. * Default : Identity.
  16791. * A Matrix is returned.
  16792. */
  16793. TransformNode.prototype.getPivotMatrix = function () {
  16794. return this._pivotMatrix;
  16795. };
  16796. /**
  16797. * Prevents the World matrix to be computed any longer.
  16798. * Returns the TransformNode.
  16799. */
  16800. TransformNode.prototype.freezeWorldMatrix = function () {
  16801. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16802. this.computeWorldMatrix(true);
  16803. this._isWorldMatrixFrozen = true;
  16804. return this;
  16805. };
  16806. /**
  16807. * Allows back the World matrix computation.
  16808. * Returns the TransformNode.
  16809. */
  16810. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16811. this._isWorldMatrixFrozen = false;
  16812. this.computeWorldMatrix(true);
  16813. return this;
  16814. };
  16815. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16816. /**
  16817. * True if the World matrix has been frozen.
  16818. * Returns a boolean.
  16819. */
  16820. get: function () {
  16821. return this._isWorldMatrixFrozen;
  16822. },
  16823. enumerable: true,
  16824. configurable: true
  16825. });
  16826. /**
  16827. * Retuns the mesh absolute position in the World.
  16828. * Returns a Vector3.
  16829. */
  16830. TransformNode.prototype.getAbsolutePosition = function () {
  16831. this.computeWorldMatrix();
  16832. return this._absolutePosition;
  16833. };
  16834. /**
  16835. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16836. * Returns the TransformNode.
  16837. */
  16838. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16839. if (!absolutePosition) {
  16840. return this;
  16841. }
  16842. var absolutePositionX;
  16843. var absolutePositionY;
  16844. var absolutePositionZ;
  16845. if (absolutePosition.x === undefined) {
  16846. if (arguments.length < 3) {
  16847. return this;
  16848. }
  16849. absolutePositionX = arguments[0];
  16850. absolutePositionY = arguments[1];
  16851. absolutePositionZ = arguments[2];
  16852. }
  16853. else {
  16854. absolutePositionX = absolutePosition.x;
  16855. absolutePositionY = absolutePosition.y;
  16856. absolutePositionZ = absolutePosition.z;
  16857. }
  16858. if (this.parent) {
  16859. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16860. invertParentWorldMatrix.invert();
  16861. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16862. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16863. }
  16864. else {
  16865. this.position.x = absolutePositionX;
  16866. this.position.y = absolutePositionY;
  16867. this.position.z = absolutePositionZ;
  16868. }
  16869. return this;
  16870. };
  16871. /**
  16872. * Sets the mesh position in its local space.
  16873. * Returns the TransformNode.
  16874. */
  16875. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16876. this.computeWorldMatrix();
  16877. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16878. return this;
  16879. };
  16880. /**
  16881. * Returns the mesh position in the local space from the current World matrix values.
  16882. * Returns a new Vector3.
  16883. */
  16884. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16885. this.computeWorldMatrix();
  16886. var invLocalWorldMatrix = this._localWorld.clone();
  16887. invLocalWorldMatrix.invert();
  16888. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16889. };
  16890. /**
  16891. * Translates the mesh along the passed Vector3 in its local space.
  16892. * Returns the TransformNode.
  16893. */
  16894. TransformNode.prototype.locallyTranslate = function (vector3) {
  16895. this.computeWorldMatrix(true);
  16896. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16897. return this;
  16898. };
  16899. /**
  16900. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16901. * @param targetPoint the position (must be in same space as current mesh) to look at
  16902. * @param yawCor optional yaw (y-axis) correction in radians
  16903. * @param pitchCor optional pitch (x-axis) correction in radians
  16904. * @param rollCor optional roll (z-axis) correction in radians
  16905. * @param space the choosen space of the target
  16906. * @returns the TransformNode.
  16907. */
  16908. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16909. if (yawCor === void 0) { yawCor = 0; }
  16910. if (pitchCor === void 0) { pitchCor = 0; }
  16911. if (rollCor === void 0) { rollCor = 0; }
  16912. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16913. var dv = TransformNode._lookAtVectorCache;
  16914. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16915. targetPoint.subtractToRef(pos, dv);
  16916. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16917. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16918. var pitch = Math.atan2(dv.y, len);
  16919. if (this.rotationQuaternion) {
  16920. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16921. }
  16922. else {
  16923. this.rotation.x = pitch + pitchCor;
  16924. this.rotation.y = yaw + yawCor;
  16925. this.rotation.z = rollCor;
  16926. }
  16927. return this;
  16928. };
  16929. /**
  16930. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16931. * This Vector3 is expressed in the World space.
  16932. */
  16933. TransformNode.prototype.getDirection = function (localAxis) {
  16934. var result = BABYLON.Vector3.Zero();
  16935. this.getDirectionToRef(localAxis, result);
  16936. return result;
  16937. };
  16938. /**
  16939. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16940. * localAxis is expressed in the mesh local space.
  16941. * result is computed in the Wordl space from the mesh World matrix.
  16942. * Returns the TransformNode.
  16943. */
  16944. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16945. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16946. return this;
  16947. };
  16948. /**
  16949. * Sets a new pivot point to the current node
  16950. * @param point defines the new pivot point to use
  16951. * @param space defines if the point is in world or local space (local by default)
  16952. * @returns the current TransformNode
  16953. */
  16954. TransformNode.prototype.setPivotPoint = function (point, space) {
  16955. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16956. if (this.getScene().getRenderId() == 0) {
  16957. this.computeWorldMatrix(true);
  16958. }
  16959. var wm = this.getWorldMatrix();
  16960. if (space == BABYLON.Space.WORLD) {
  16961. var tmat = BABYLON.Tmp.Matrix[0];
  16962. wm.invertToRef(tmat);
  16963. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16964. }
  16965. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16966. };
  16967. /**
  16968. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16969. */
  16970. TransformNode.prototype.getPivotPoint = function () {
  16971. var point = BABYLON.Vector3.Zero();
  16972. this.getPivotPointToRef(point);
  16973. return point;
  16974. };
  16975. /**
  16976. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16977. * Returns the TransformNode.
  16978. */
  16979. TransformNode.prototype.getPivotPointToRef = function (result) {
  16980. result.x = -this._pivotMatrix.m[12];
  16981. result.y = -this._pivotMatrix.m[13];
  16982. result.z = -this._pivotMatrix.m[14];
  16983. return this;
  16984. };
  16985. /**
  16986. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16987. */
  16988. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16989. var point = BABYLON.Vector3.Zero();
  16990. this.getAbsolutePivotPointToRef(point);
  16991. return point;
  16992. };
  16993. /**
  16994. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16995. * Returns the TransformNode.
  16996. */
  16997. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16998. result.x = this._pivotMatrix.m[12];
  16999. result.y = this._pivotMatrix.m[13];
  17000. result.z = this._pivotMatrix.m[14];
  17001. this.getPivotPointToRef(result);
  17002. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17003. return this;
  17004. };
  17005. /**
  17006. * Defines the passed node as the parent of the current node.
  17007. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17008. * Returns the TransformNode.
  17009. */
  17010. TransformNode.prototype.setParent = function (node) {
  17011. if (node === null) {
  17012. var rotation = BABYLON.Tmp.Quaternion[0];
  17013. var position = BABYLON.Tmp.Vector3[0];
  17014. var scale = BABYLON.Tmp.Vector3[1];
  17015. if (this.parent && this.parent.computeWorldMatrix) {
  17016. this.parent.computeWorldMatrix(true);
  17017. }
  17018. this.computeWorldMatrix(true);
  17019. this.getWorldMatrix().decompose(scale, rotation, position);
  17020. if (this.rotationQuaternion) {
  17021. this.rotationQuaternion.copyFrom(rotation);
  17022. }
  17023. else {
  17024. rotation.toEulerAnglesToRef(this.rotation);
  17025. }
  17026. this.scaling.x = scale.x;
  17027. this.scaling.y = scale.y;
  17028. this.scaling.z = scale.z;
  17029. this.position.x = position.x;
  17030. this.position.y = position.y;
  17031. this.position.z = position.z;
  17032. }
  17033. else {
  17034. var rotation = BABYLON.Tmp.Quaternion[0];
  17035. var position = BABYLON.Tmp.Vector3[0];
  17036. var scale = BABYLON.Tmp.Vector3[1];
  17037. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17038. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17039. this.computeWorldMatrix(true);
  17040. node.computeWorldMatrix(true);
  17041. node.getWorldMatrix().invertToRef(invParentMatrix);
  17042. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17043. diffMatrix.decompose(scale, rotation, position);
  17044. if (this.rotationQuaternion) {
  17045. this.rotationQuaternion.copyFrom(rotation);
  17046. }
  17047. else {
  17048. rotation.toEulerAnglesToRef(this.rotation);
  17049. }
  17050. this.position.x = position.x;
  17051. this.position.y = position.y;
  17052. this.position.z = position.z;
  17053. this.scaling.x = scale.x;
  17054. this.scaling.y = scale.y;
  17055. this.scaling.z = scale.z;
  17056. }
  17057. this.parent = node;
  17058. return this;
  17059. };
  17060. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17061. get: function () {
  17062. return this._nonUniformScaling;
  17063. },
  17064. enumerable: true,
  17065. configurable: true
  17066. });
  17067. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17068. if (this._nonUniformScaling === value) {
  17069. return false;
  17070. }
  17071. this._nonUniformScaling = true;
  17072. return true;
  17073. };
  17074. /**
  17075. * Attach the current TransformNode to another TransformNode associated with a bone
  17076. * @param bone Bone affecting the TransformNode
  17077. * @param affectedTransformNode TransformNode associated with the bone
  17078. */
  17079. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17080. this._transformToBoneReferal = affectedTransformNode;
  17081. this.parent = bone;
  17082. if (bone.getWorldMatrix().determinant() < 0) {
  17083. this.scalingDeterminant *= -1;
  17084. }
  17085. return this;
  17086. };
  17087. TransformNode.prototype.detachFromBone = function () {
  17088. if (!this.parent) {
  17089. return this;
  17090. }
  17091. if (this.parent.getWorldMatrix().determinant() < 0) {
  17092. this.scalingDeterminant *= -1;
  17093. }
  17094. this._transformToBoneReferal = null;
  17095. this.parent = null;
  17096. return this;
  17097. };
  17098. /**
  17099. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17100. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17101. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17102. * The passed axis is also normalized.
  17103. * Returns the TransformNode.
  17104. */
  17105. TransformNode.prototype.rotate = function (axis, amount, space) {
  17106. axis.normalize();
  17107. if (!this.rotationQuaternion) {
  17108. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17109. this.rotation = BABYLON.Vector3.Zero();
  17110. }
  17111. var rotationQuaternion;
  17112. if (!space || space === BABYLON.Space.LOCAL) {
  17113. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17114. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17115. }
  17116. else {
  17117. if (this.parent) {
  17118. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17119. invertParentWorldMatrix.invert();
  17120. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17121. }
  17122. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17123. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17124. }
  17125. return this;
  17126. };
  17127. /**
  17128. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17129. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17130. * The passed axis is also normalized.
  17131. * Returns the TransformNode.
  17132. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17133. */
  17134. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17135. axis.normalize();
  17136. if (!this.rotationQuaternion) {
  17137. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17138. this.rotation.copyFromFloats(0, 0, 0);
  17139. }
  17140. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17141. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17142. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17143. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17144. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17145. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17146. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17147. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17148. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17149. return this;
  17150. };
  17151. /**
  17152. * Translates the mesh along the axis vector for the passed distance in the given space.
  17153. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17154. * Returns the TransformNode.
  17155. */
  17156. TransformNode.prototype.translate = function (axis, distance, space) {
  17157. var displacementVector = axis.scale(distance);
  17158. if (!space || space === BABYLON.Space.LOCAL) {
  17159. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17160. this.setPositionWithLocalVector(tempV3);
  17161. }
  17162. else {
  17163. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17164. }
  17165. return this;
  17166. };
  17167. /**
  17168. * Adds a rotation step to the mesh current rotation.
  17169. * x, y, z are Euler angles expressed in radians.
  17170. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17171. * This means this rotation is made in the mesh local space only.
  17172. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17173. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17174. * ```javascript
  17175. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17176. * ```
  17177. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17178. * 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.
  17179. * Returns the TransformNode.
  17180. */
  17181. TransformNode.prototype.addRotation = function (x, y, z) {
  17182. var rotationQuaternion;
  17183. if (this.rotationQuaternion) {
  17184. rotationQuaternion = this.rotationQuaternion;
  17185. }
  17186. else {
  17187. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17188. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17189. }
  17190. var accumulation = BABYLON.Tmp.Quaternion[0];
  17191. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17192. rotationQuaternion.multiplyInPlace(accumulation);
  17193. if (!this.rotationQuaternion) {
  17194. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17195. }
  17196. return this;
  17197. };
  17198. /**
  17199. * Computes the mesh World matrix and returns it.
  17200. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17201. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17202. * If the parameter `force`is set to `true`, the actual computation is done.
  17203. * Returns the mesh World Matrix.
  17204. */
  17205. TransformNode.prototype.computeWorldMatrix = function (force) {
  17206. if (this._isWorldMatrixFrozen) {
  17207. return this._worldMatrix;
  17208. }
  17209. if (!force && this.isSynchronized(true)) {
  17210. this._currentRenderId = this.getScene().getRenderId();
  17211. return this._worldMatrix;
  17212. }
  17213. this._cache.position.copyFrom(this.position);
  17214. this._cache.scaling.copyFrom(this.scaling);
  17215. this._cache.pivotMatrixUpdated = false;
  17216. this._cache.billboardMode = this.billboardMode;
  17217. this._currentRenderId = this.getScene().getRenderId();
  17218. this._childRenderId = this.getScene().getRenderId();
  17219. this._isDirty = false;
  17220. // Scaling
  17221. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17222. // Rotation
  17223. //rotate, if quaternion is set and rotation was used
  17224. if (this.rotationQuaternion) {
  17225. var len = this.rotation.length();
  17226. if (len) {
  17227. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17228. this.rotation.copyFromFloats(0, 0, 0);
  17229. }
  17230. }
  17231. if (this.rotationQuaternion) {
  17232. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17233. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17234. }
  17235. else {
  17236. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17237. this._cache.rotation.copyFrom(this.rotation);
  17238. }
  17239. // Translation
  17240. var camera = this.getScene().activeCamera;
  17241. if (this.infiniteDistance && !this.parent && camera) {
  17242. var cameraWorldMatrix = camera.getWorldMatrix();
  17243. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17244. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17245. }
  17246. else {
  17247. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17248. }
  17249. // Composing transformations
  17250. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17251. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17252. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17253. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  17254. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  17255. // Need to decompose each rotation here
  17256. var currentPosition = BABYLON.Tmp.Vector3[3];
  17257. if (this.parent && this.parent.getWorldMatrix) {
  17258. if (this._transformToBoneReferal) {
  17259. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17260. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17261. }
  17262. else {
  17263. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17264. }
  17265. }
  17266. else {
  17267. currentPosition.copyFrom(this.position);
  17268. }
  17269. currentPosition.subtractInPlace(camera.globalPosition);
  17270. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17271. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  17272. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17273. }
  17274. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  17275. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17276. }
  17277. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  17278. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17279. }
  17280. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17281. }
  17282. else {
  17283. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17284. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17285. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17286. }
  17287. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17288. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17289. }
  17290. // Local world
  17291. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17292. // Parent
  17293. if (this.parent && this.parent.getWorldMatrix) {
  17294. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  17295. if (this._transformToBoneReferal) {
  17296. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17297. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17298. }
  17299. else {
  17300. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17301. }
  17302. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17303. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17304. this._worldMatrix.copyFrom(this._localWorld);
  17305. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17306. }
  17307. else {
  17308. if (this._transformToBoneReferal) {
  17309. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17310. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17311. }
  17312. else {
  17313. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17314. }
  17315. }
  17316. this._markSyncedWithParent();
  17317. }
  17318. else {
  17319. this._worldMatrix.copyFrom(this._localWorld);
  17320. }
  17321. // Post multiply inverse of pivotMatrix
  17322. if (this._postMultiplyPivotMatrix) {
  17323. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17324. }
  17325. // Normal matrix
  17326. if (this.scaling.isNonUniform) {
  17327. this._updateNonUniformScalingState(true);
  17328. }
  17329. else if (this.parent && this.parent._nonUniformScaling) {
  17330. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17331. }
  17332. else {
  17333. this._updateNonUniformScalingState(false);
  17334. }
  17335. this._afterComputeWorldMatrix();
  17336. // Absolute position
  17337. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17338. // Callbacks
  17339. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17340. if (!this._poseMatrix) {
  17341. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17342. }
  17343. // Cache the determinant
  17344. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17345. return this._worldMatrix;
  17346. };
  17347. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17348. };
  17349. /**
  17350. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17351. * @param func: callback function to add
  17352. *
  17353. * Returns the TransformNode.
  17354. */
  17355. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17356. this.onAfterWorldMatrixUpdateObservable.add(func);
  17357. return this;
  17358. };
  17359. /**
  17360. * Removes a registered callback function.
  17361. * Returns the TransformNode.
  17362. */
  17363. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17364. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17365. return this;
  17366. };
  17367. /**
  17368. * Clone the current transform node
  17369. * Returns the new transform node
  17370. * @param name Name of the new clone
  17371. * @param newParent New parent for the clone
  17372. * @param doNotCloneChildren Do not clone children hierarchy
  17373. */
  17374. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17375. var _this = this;
  17376. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17377. result.name = name;
  17378. result.id = name;
  17379. if (newParent) {
  17380. result.parent = newParent;
  17381. }
  17382. if (!doNotCloneChildren) {
  17383. // Children
  17384. var directDescendants = this.getDescendants(true);
  17385. for (var index = 0; index < directDescendants.length; index++) {
  17386. var child = directDescendants[index];
  17387. if (child.clone) {
  17388. child.clone(name + "." + child.name, result);
  17389. }
  17390. }
  17391. }
  17392. return result;
  17393. };
  17394. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17395. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17396. serializationObject.type = this.getClassName();
  17397. // Parent
  17398. if (this.parent) {
  17399. serializationObject.parentId = this.parent.id;
  17400. }
  17401. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17402. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17403. }
  17404. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17405. serializationObject.isEnabled = this.isEnabled();
  17406. // Parent
  17407. if (this.parent) {
  17408. serializationObject.parentId = this.parent.id;
  17409. }
  17410. return serializationObject;
  17411. };
  17412. // Statics
  17413. /**
  17414. * Returns a new TransformNode object parsed from the source provided.
  17415. * The parameter `parsedMesh` is the source.
  17416. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17417. */
  17418. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17419. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17420. if (BABYLON.Tags) {
  17421. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17422. }
  17423. if (parsedTransformNode.localMatrix) {
  17424. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17425. }
  17426. else if (parsedTransformNode.pivotMatrix) {
  17427. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17428. }
  17429. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17430. // Parent
  17431. if (parsedTransformNode.parentId) {
  17432. transformNode._waitingParentId = parsedTransformNode.parentId;
  17433. }
  17434. return transformNode;
  17435. };
  17436. /**
  17437. * Releases resources associated with this transform node.
  17438. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17439. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17440. */
  17441. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17442. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17443. // Animations
  17444. this.getScene().stopAnimation(this);
  17445. // Remove from scene
  17446. this.getScene().removeTransformNode(this);
  17447. this.onAfterWorldMatrixUpdateObservable.clear();
  17448. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17449. };
  17450. // Statics
  17451. TransformNode.BILLBOARDMODE_NONE = 0;
  17452. TransformNode.BILLBOARDMODE_X = 1;
  17453. TransformNode.BILLBOARDMODE_Y = 2;
  17454. TransformNode.BILLBOARDMODE_Z = 4;
  17455. TransformNode.BILLBOARDMODE_ALL = 7;
  17456. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17457. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17458. __decorate([
  17459. BABYLON.serializeAsVector3()
  17460. ], TransformNode.prototype, "_rotation", void 0);
  17461. __decorate([
  17462. BABYLON.serializeAsQuaternion()
  17463. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17464. __decorate([
  17465. BABYLON.serializeAsVector3()
  17466. ], TransformNode.prototype, "_scaling", void 0);
  17467. __decorate([
  17468. BABYLON.serialize()
  17469. ], TransformNode.prototype, "billboardMode", void 0);
  17470. __decorate([
  17471. BABYLON.serialize()
  17472. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17473. __decorate([
  17474. BABYLON.serialize()
  17475. ], TransformNode.prototype, "infiniteDistance", void 0);
  17476. __decorate([
  17477. BABYLON.serializeAsVector3()
  17478. ], TransformNode.prototype, "position", void 0);
  17479. return TransformNode;
  17480. }(BABYLON.Node));
  17481. BABYLON.TransformNode = TransformNode;
  17482. })(BABYLON || (BABYLON = {}));
  17483. //# sourceMappingURL=babylon.transformNode.js.map
  17484. "use strict";
  17485. var BABYLON;
  17486. (function (BABYLON) {
  17487. var AbstractMesh = /** @class */ (function (_super) {
  17488. __extends(AbstractMesh, _super);
  17489. // Constructor
  17490. function AbstractMesh(name, scene) {
  17491. if (scene === void 0) { scene = null; }
  17492. var _this = _super.call(this, name, scene, false) || this;
  17493. _this._facetNb = 0; // facet number
  17494. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17495. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17496. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17497. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17498. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17499. _this._subDiv = {
  17500. max: 1,
  17501. X: 1,
  17502. Y: 1,
  17503. Z: 1
  17504. };
  17505. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17506. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17507. // Events
  17508. /**
  17509. * An event triggered when this mesh collides with another one
  17510. * @type {BABYLON.Observable}
  17511. */
  17512. _this.onCollideObservable = new BABYLON.Observable();
  17513. /**
  17514. * An event triggered when the collision's position changes
  17515. * @type {BABYLON.Observable}
  17516. */
  17517. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17518. /**
  17519. * An event triggered when material is changed
  17520. * @type {BABYLON.Observable}
  17521. */
  17522. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17523. // Properties
  17524. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17525. /**
  17526. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17527. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17528. * or
  17529. * 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.
  17530. * for more info check WebGl documentations
  17531. */
  17532. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17533. /**
  17534. * 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:
  17535. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17536. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17537. * 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.
  17538. */
  17539. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17540. /**
  17541. * 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.
  17542. * The default value is -1 which means don't break the query and wait till the result.
  17543. */
  17544. _this.occlusionRetryCount = -1;
  17545. _this._occlusionInternalRetryCounter = 0;
  17546. _this._isOccluded = false;
  17547. _this._isOcclusionQueryInProgress = false;
  17548. _this._visibility = 1.0;
  17549. _this.alphaIndex = Number.MAX_VALUE;
  17550. _this.isVisible = true;
  17551. _this.isPickable = true;
  17552. _this.showBoundingBox = false;
  17553. _this.showSubMeshesBoundingBox = false;
  17554. _this.isBlocker = false;
  17555. _this.enablePointerMoveEvents = false;
  17556. _this.renderingGroupId = 0;
  17557. _this._receiveShadows = false;
  17558. _this.renderOutline = false;
  17559. _this.outlineColor = BABYLON.Color3.Red();
  17560. _this.outlineWidth = 0.02;
  17561. _this.renderOverlay = false;
  17562. _this.overlayColor = BABYLON.Color3.Red();
  17563. _this.overlayAlpha = 0.5;
  17564. _this._hasVertexAlpha = false;
  17565. _this._useVertexColors = true;
  17566. _this._computeBonesUsingShaders = true;
  17567. _this._numBoneInfluencers = 4;
  17568. _this._applyFog = true;
  17569. _this.useOctreeForRenderingSelection = true;
  17570. _this.useOctreeForPicking = true;
  17571. _this.useOctreeForCollisions = true;
  17572. _this._layerMask = 0x0FFFFFFF;
  17573. /**
  17574. * True if the mesh must be rendered in any case.
  17575. */
  17576. _this.alwaysSelectAsActiveMesh = false;
  17577. /**
  17578. * This scene's action manager
  17579. * @type {BABYLON.ActionManager}
  17580. */
  17581. _this.actionManager = null;
  17582. // Physics
  17583. _this.physicsImpostor = null;
  17584. // Collisions
  17585. _this._checkCollisions = false;
  17586. _this._collisionMask = -1;
  17587. _this._collisionGroup = -1;
  17588. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17589. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17590. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17591. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17592. // Edges
  17593. _this.edgesWidth = 1;
  17594. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17595. // Cache
  17596. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17597. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17598. _this._renderId = 0;
  17599. _this._intersectionsInProgress = new Array();
  17600. _this._unIndexed = false;
  17601. _this._lightSources = new Array();
  17602. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17603. if (collidedMesh === void 0) { collidedMesh = null; }
  17604. //TODO move this to the collision coordinator!
  17605. if (_this.getScene().workerCollisions)
  17606. newPosition.multiplyInPlace(_this._collider._radius);
  17607. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17608. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17609. _this.position.addInPlace(_this._diffPositionForCollisions);
  17610. }
  17611. if (collidedMesh) {
  17612. _this.onCollideObservable.notifyObservers(collidedMesh);
  17613. }
  17614. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17615. };
  17616. _this.getScene().addMesh(_this);
  17617. _this._resyncLightSources();
  17618. return _this;
  17619. }
  17620. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17621. get: function () {
  17622. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17623. },
  17624. enumerable: true,
  17625. configurable: true
  17626. });
  17627. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17628. get: function () {
  17629. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17635. get: function () {
  17636. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17642. get: function () {
  17643. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17649. get: function () {
  17650. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17656. /**
  17657. * Read-only : the number of facets in the mesh
  17658. */
  17659. get: function () {
  17660. return this._facetNb;
  17661. },
  17662. enumerable: true,
  17663. configurable: true
  17664. });
  17665. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17666. /**
  17667. * The number (integer) of subdivisions per axis in the partioning space
  17668. */
  17669. get: function () {
  17670. return this._partitioningSubdivisions;
  17671. },
  17672. set: function (nb) {
  17673. this._partitioningSubdivisions = nb;
  17674. },
  17675. enumerable: true,
  17676. configurable: true
  17677. });
  17678. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17679. /**
  17680. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17681. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17682. */
  17683. get: function () {
  17684. return this._partitioningBBoxRatio;
  17685. },
  17686. set: function (ratio) {
  17687. this._partitioningBBoxRatio = ratio;
  17688. },
  17689. enumerable: true,
  17690. configurable: true
  17691. });
  17692. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17693. /**
  17694. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17695. * Works only for updatable meshes.
  17696. * Doesn't work with multi-materials.
  17697. */
  17698. get: function () {
  17699. return this._facetDepthSort;
  17700. },
  17701. set: function (sort) {
  17702. this._facetDepthSort = sort;
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17708. /**
  17709. * The location (Vector3) where the facet depth sort must be computed from.
  17710. * By default, the active camera position.
  17711. * Used only when facet depth sort is enabled.
  17712. */
  17713. get: function () {
  17714. return this._facetDepthSortFrom;
  17715. },
  17716. set: function (location) {
  17717. this._facetDepthSortFrom = location;
  17718. },
  17719. enumerable: true,
  17720. configurable: true
  17721. });
  17722. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17723. /**
  17724. * Read-only boolean : is the feature facetData enabled ?
  17725. */
  17726. get: function () {
  17727. return this._facetDataEnabled;
  17728. },
  17729. enumerable: true,
  17730. configurable: true
  17731. });
  17732. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17733. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17734. return false;
  17735. }
  17736. this._markSubMeshesAsMiscDirty();
  17737. return true;
  17738. };
  17739. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17740. set: function (callback) {
  17741. if (this._onCollideObserver) {
  17742. this.onCollideObservable.remove(this._onCollideObserver);
  17743. }
  17744. this._onCollideObserver = this.onCollideObservable.add(callback);
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17750. set: function (callback) {
  17751. if (this._onCollisionPositionChangeObserver) {
  17752. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17753. }
  17754. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17755. },
  17756. enumerable: true,
  17757. configurable: true
  17758. });
  17759. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17760. /**
  17761. * 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.
  17762. */
  17763. get: function () {
  17764. return this._isOccluded;
  17765. },
  17766. set: function (value) {
  17767. this._isOccluded = value;
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17773. /**
  17774. * Flag to check the progress status of the query
  17775. */
  17776. get: function () {
  17777. return this._isOcclusionQueryInProgress;
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17783. /**
  17784. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17785. */
  17786. get: function () {
  17787. return this._visibility;
  17788. },
  17789. /**
  17790. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17791. */
  17792. set: function (value) {
  17793. if (this._visibility === value) {
  17794. return;
  17795. }
  17796. this._visibility = value;
  17797. this._markSubMeshesAsMiscDirty();
  17798. },
  17799. enumerable: true,
  17800. configurable: true
  17801. });
  17802. Object.defineProperty(AbstractMesh.prototype, "material", {
  17803. get: function () {
  17804. return this._material;
  17805. },
  17806. set: function (value) {
  17807. if (this._material === value) {
  17808. return;
  17809. }
  17810. this._material = value;
  17811. if (this.onMaterialChangedObservable.hasObservers) {
  17812. this.onMaterialChangedObservable.notifyObservers(this);
  17813. }
  17814. if (!this.subMeshes) {
  17815. return;
  17816. }
  17817. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17818. var subMesh = _a[_i];
  17819. subMesh.setEffect(null);
  17820. }
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17826. get: function () {
  17827. return this._receiveShadows;
  17828. },
  17829. set: function (value) {
  17830. if (this._receiveShadows === value) {
  17831. return;
  17832. }
  17833. this._receiveShadows = value;
  17834. this._markSubMeshesAsLightDirty();
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17840. get: function () {
  17841. return this._hasVertexAlpha;
  17842. },
  17843. set: function (value) {
  17844. if (this._hasVertexAlpha === value) {
  17845. return;
  17846. }
  17847. this._hasVertexAlpha = value;
  17848. this._markSubMeshesAsAttributesDirty();
  17849. this._markSubMeshesAsMiscDirty();
  17850. },
  17851. enumerable: true,
  17852. configurable: true
  17853. });
  17854. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17855. get: function () {
  17856. return this._useVertexColors;
  17857. },
  17858. set: function (value) {
  17859. if (this._useVertexColors === value) {
  17860. return;
  17861. }
  17862. this._useVertexColors = value;
  17863. this._markSubMeshesAsAttributesDirty();
  17864. },
  17865. enumerable: true,
  17866. configurable: true
  17867. });
  17868. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17869. get: function () {
  17870. return this._computeBonesUsingShaders;
  17871. },
  17872. set: function (value) {
  17873. if (this._computeBonesUsingShaders === value) {
  17874. return;
  17875. }
  17876. this._computeBonesUsingShaders = value;
  17877. this._markSubMeshesAsAttributesDirty();
  17878. },
  17879. enumerable: true,
  17880. configurable: true
  17881. });
  17882. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17883. get: function () {
  17884. return this._numBoneInfluencers;
  17885. },
  17886. set: function (value) {
  17887. if (this._numBoneInfluencers === value) {
  17888. return;
  17889. }
  17890. this._numBoneInfluencers = value;
  17891. this._markSubMeshesAsAttributesDirty();
  17892. },
  17893. enumerable: true,
  17894. configurable: true
  17895. });
  17896. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17897. get: function () {
  17898. return this._applyFog;
  17899. },
  17900. set: function (value) {
  17901. if (this._applyFog === value) {
  17902. return;
  17903. }
  17904. this._applyFog = value;
  17905. this._markSubMeshesAsMiscDirty();
  17906. },
  17907. enumerable: true,
  17908. configurable: true
  17909. });
  17910. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17911. get: function () {
  17912. return this._layerMask;
  17913. },
  17914. set: function (value) {
  17915. if (value === this._layerMask) {
  17916. return;
  17917. }
  17918. this._layerMask = value;
  17919. this._resyncLightSources();
  17920. },
  17921. enumerable: true,
  17922. configurable: true
  17923. });
  17924. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17925. get: function () {
  17926. return this._collisionMask;
  17927. },
  17928. set: function (mask) {
  17929. this._collisionMask = !isNaN(mask) ? mask : -1;
  17930. },
  17931. enumerable: true,
  17932. configurable: true
  17933. });
  17934. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17935. get: function () {
  17936. return this._collisionGroup;
  17937. },
  17938. set: function (mask) {
  17939. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17940. },
  17941. enumerable: true,
  17942. configurable: true
  17943. });
  17944. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17945. get: function () {
  17946. return null;
  17947. },
  17948. enumerable: true,
  17949. configurable: true
  17950. });
  17951. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17952. get: function () {
  17953. return this._skeleton;
  17954. },
  17955. set: function (value) {
  17956. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17957. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17958. }
  17959. if (value && value.needInitialSkinMatrix) {
  17960. value._registerMeshWithPoseMatrix(this);
  17961. }
  17962. this._skeleton = value;
  17963. if (!this._skeleton) {
  17964. this._bonesTransformMatrices = null;
  17965. }
  17966. this._markSubMeshesAsAttributesDirty();
  17967. },
  17968. enumerable: true,
  17969. configurable: true
  17970. });
  17971. /**
  17972. * Returns the string "AbstractMesh"
  17973. */
  17974. AbstractMesh.prototype.getClassName = function () {
  17975. return "AbstractMesh";
  17976. };
  17977. /**
  17978. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17979. */
  17980. AbstractMesh.prototype.toString = function (fullDetails) {
  17981. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17982. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17983. if (this._skeleton) {
  17984. ret += ", skeleton: " + this._skeleton.name;
  17985. }
  17986. if (fullDetails) {
  17987. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17988. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17989. }
  17990. return ret;
  17991. };
  17992. AbstractMesh.prototype._rebuild = function () {
  17993. if (this._occlusionQuery) {
  17994. this._occlusionQuery = null;
  17995. }
  17996. if (this._edgesRenderer) {
  17997. this._edgesRenderer._rebuild();
  17998. }
  17999. if (!this.subMeshes) {
  18000. return;
  18001. }
  18002. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18003. var subMesh = _a[_i];
  18004. subMesh._rebuild();
  18005. }
  18006. };
  18007. AbstractMesh.prototype._resyncLightSources = function () {
  18008. this._lightSources.length = 0;
  18009. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18010. var light = _a[_i];
  18011. if (!light.isEnabled()) {
  18012. continue;
  18013. }
  18014. if (light.canAffectMesh(this)) {
  18015. this._lightSources.push(light);
  18016. }
  18017. }
  18018. this._markSubMeshesAsLightDirty();
  18019. };
  18020. AbstractMesh.prototype._resyncLighSource = function (light) {
  18021. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18022. var index = this._lightSources.indexOf(light);
  18023. if (index === -1) {
  18024. if (!isIn) {
  18025. return;
  18026. }
  18027. this._lightSources.push(light);
  18028. }
  18029. else {
  18030. if (isIn) {
  18031. return;
  18032. }
  18033. this._lightSources.splice(index, 1);
  18034. }
  18035. this._markSubMeshesAsLightDirty();
  18036. };
  18037. AbstractMesh.prototype._removeLightSource = function (light) {
  18038. var index = this._lightSources.indexOf(light);
  18039. if (index === -1) {
  18040. return;
  18041. }
  18042. this._lightSources.splice(index, 1);
  18043. this._markSubMeshesAsLightDirty();
  18044. };
  18045. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18046. if (!this.subMeshes) {
  18047. return;
  18048. }
  18049. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18050. var subMesh = _a[_i];
  18051. if (subMesh._materialDefines) {
  18052. func(subMesh._materialDefines);
  18053. }
  18054. }
  18055. };
  18056. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18057. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18058. };
  18059. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18060. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18061. };
  18062. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18063. if (!this.subMeshes) {
  18064. return;
  18065. }
  18066. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18067. var subMesh = _a[_i];
  18068. var material = subMesh.getMaterial();
  18069. if (material) {
  18070. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18071. }
  18072. }
  18073. };
  18074. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18075. /**
  18076. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18077. * Default : (1.0, 1.0, 1.0)
  18078. */
  18079. get: function () {
  18080. return this._scaling;
  18081. },
  18082. /**
  18083. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18084. * Default : (1.0, 1.0, 1.0)
  18085. */
  18086. set: function (newScaling) {
  18087. this._scaling = newScaling;
  18088. if (this.physicsImpostor) {
  18089. this.physicsImpostor.forceUpdate();
  18090. }
  18091. },
  18092. enumerable: true,
  18093. configurable: true
  18094. });
  18095. // Methods
  18096. /**
  18097. * Disables the mesh edger rendering mode.
  18098. * Returns the AbstractMesh.
  18099. */
  18100. AbstractMesh.prototype.disableEdgesRendering = function () {
  18101. if (this._edgesRenderer) {
  18102. this._edgesRenderer.dispose();
  18103. this._edgesRenderer = null;
  18104. }
  18105. return this;
  18106. };
  18107. /**
  18108. * Enables the edge rendering mode on the mesh.
  18109. * This mode makes the mesh edges visible.
  18110. * Returns the AbstractMesh.
  18111. */
  18112. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18113. if (epsilon === void 0) { epsilon = 0.95; }
  18114. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18115. this.disableEdgesRendering();
  18116. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18117. return this;
  18118. };
  18119. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18120. /**
  18121. * Returns true if the mesh is blocked. Used by the class Mesh.
  18122. * Returns the boolean `false` by default.
  18123. */
  18124. get: function () {
  18125. return false;
  18126. },
  18127. enumerable: true,
  18128. configurable: true
  18129. });
  18130. /**
  18131. * Returns the mesh itself by default, used by the class Mesh.
  18132. * Returned type : AbstractMesh
  18133. */
  18134. AbstractMesh.prototype.getLOD = function (camera) {
  18135. return this;
  18136. };
  18137. /**
  18138. * Returns 0 by default, used by the class Mesh.
  18139. * Returns an integer.
  18140. */
  18141. AbstractMesh.prototype.getTotalVertices = function () {
  18142. return 0;
  18143. };
  18144. /**
  18145. * Returns null by default, used by the class Mesh.
  18146. * Returned type : integer array
  18147. */
  18148. AbstractMesh.prototype.getIndices = function () {
  18149. return null;
  18150. };
  18151. /**
  18152. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18153. * Returned type : float array or Float32Array
  18154. */
  18155. AbstractMesh.prototype.getVerticesData = function (kind) {
  18156. return null;
  18157. };
  18158. /**
  18159. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18160. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18161. * The `data` are either a numeric array either a Float32Array.
  18162. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18163. * 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).
  18164. * Note that a new underlying VertexBuffer object is created each call.
  18165. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18166. *
  18167. * Possible `kind` values :
  18168. * - BABYLON.VertexBuffer.PositionKind
  18169. * - BABYLON.VertexBuffer.UVKind
  18170. * - BABYLON.VertexBuffer.UV2Kind
  18171. * - BABYLON.VertexBuffer.UV3Kind
  18172. * - BABYLON.VertexBuffer.UV4Kind
  18173. * - BABYLON.VertexBuffer.UV5Kind
  18174. * - BABYLON.VertexBuffer.UV6Kind
  18175. * - BABYLON.VertexBuffer.ColorKind
  18176. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18177. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18178. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18179. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18180. *
  18181. * Returns the Mesh.
  18182. */
  18183. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18184. return this;
  18185. };
  18186. /**
  18187. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18188. * If the mesh has no geometry, it is simply returned as it is.
  18189. * The `data` are either a numeric array either a Float32Array.
  18190. * No new underlying VertexBuffer object is created.
  18191. * 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.
  18192. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18193. *
  18194. * Possible `kind` values :
  18195. * - BABYLON.VertexBuffer.PositionKind
  18196. * - BABYLON.VertexBuffer.UVKind
  18197. * - BABYLON.VertexBuffer.UV2Kind
  18198. * - BABYLON.VertexBuffer.UV3Kind
  18199. * - BABYLON.VertexBuffer.UV4Kind
  18200. * - BABYLON.VertexBuffer.UV5Kind
  18201. * - BABYLON.VertexBuffer.UV6Kind
  18202. * - BABYLON.VertexBuffer.ColorKind
  18203. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18204. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18205. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18206. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18207. *
  18208. * Returns the Mesh.
  18209. */
  18210. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18211. return this;
  18212. };
  18213. /**
  18214. * Sets the mesh indices.
  18215. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18216. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18217. * This method creates a new index buffer each call.
  18218. * Returns the Mesh.
  18219. */
  18220. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18221. return this;
  18222. };
  18223. /** Returns false by default, used by the class Mesh.
  18224. * Returns a boolean
  18225. */
  18226. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18227. return false;
  18228. };
  18229. /**
  18230. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18231. * Returns a BoundingInfo
  18232. */
  18233. AbstractMesh.prototype.getBoundingInfo = function () {
  18234. if (this._masterMesh) {
  18235. return this._masterMesh.getBoundingInfo();
  18236. }
  18237. if (!this._boundingInfo) {
  18238. // this._boundingInfo is being created here
  18239. this._updateBoundingInfo();
  18240. }
  18241. // cannot be null.
  18242. return this._boundingInfo;
  18243. };
  18244. /**
  18245. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18246. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18247. */
  18248. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18249. if (includeDescendants === void 0) { includeDescendants = true; }
  18250. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18251. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18252. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18253. if (maxDimension === 0) {
  18254. return this;
  18255. }
  18256. var scale = 1 / maxDimension;
  18257. this.scaling.scaleInPlace(scale);
  18258. return this;
  18259. };
  18260. /**
  18261. * Sets a mesh new object BoundingInfo.
  18262. * Returns the AbstractMesh.
  18263. */
  18264. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18265. this._boundingInfo = boundingInfo;
  18266. return this;
  18267. };
  18268. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18269. get: function () {
  18270. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18271. },
  18272. enumerable: true,
  18273. configurable: true
  18274. });
  18275. AbstractMesh.prototype._preActivate = function () {
  18276. };
  18277. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18278. };
  18279. AbstractMesh.prototype._activate = function (renderId) {
  18280. this._renderId = renderId;
  18281. };
  18282. /**
  18283. * Returns the latest update of the World matrix
  18284. * Returns a Matrix.
  18285. */
  18286. AbstractMesh.prototype.getWorldMatrix = function () {
  18287. if (this._masterMesh) {
  18288. return this._masterMesh.getWorldMatrix();
  18289. }
  18290. return _super.prototype.getWorldMatrix.call(this);
  18291. };
  18292. /**
  18293. * Returns the latest update of the World matrix determinant.
  18294. */
  18295. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18296. if (this._masterMesh) {
  18297. return this._masterMesh._getWorldMatrixDeterminant();
  18298. }
  18299. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18300. };
  18301. // ================================== Point of View Movement =================================
  18302. /**
  18303. * Perform relative position change from the point of view of behind the front of the mesh.
  18304. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18305. * Supports definition of mesh facing forward or backward.
  18306. * @param {number} amountRight
  18307. * @param {number} amountUp
  18308. * @param {number} amountForward
  18309. *
  18310. * Returns the AbstractMesh.
  18311. */
  18312. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18313. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18314. return this;
  18315. };
  18316. /**
  18317. * Calculate relative position change from the point of view of behind the front of the mesh.
  18318. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18319. * Supports definition of mesh facing forward or backward.
  18320. * @param {number} amountRight
  18321. * @param {number} amountUp
  18322. * @param {number} amountForward
  18323. *
  18324. * Returns a new Vector3.
  18325. */
  18326. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18327. var rotMatrix = new BABYLON.Matrix();
  18328. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18329. rotQuaternion.toRotationMatrix(rotMatrix);
  18330. var translationDelta = BABYLON.Vector3.Zero();
  18331. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18332. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18333. return translationDelta;
  18334. };
  18335. // ================================== Point of View Rotation =================================
  18336. /**
  18337. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18338. * Supports definition of mesh facing forward or backward.
  18339. * @param {number} flipBack
  18340. * @param {number} twirlClockwise
  18341. * @param {number} tiltRight
  18342. *
  18343. * Returns the AbstractMesh.
  18344. */
  18345. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18346. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18347. return this;
  18348. };
  18349. /**
  18350. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18351. * Supports definition of mesh facing forward or backward.
  18352. * @param {number} flipBack
  18353. * @param {number} twirlClockwise
  18354. * @param {number} tiltRight
  18355. *
  18356. * Returns a new Vector3.
  18357. */
  18358. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18359. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18360. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18361. };
  18362. /**
  18363. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18364. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18365. */
  18366. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18367. if (includeDescendants === void 0) { includeDescendants = true; }
  18368. this.computeWorldMatrix(true);
  18369. var min;
  18370. var max;
  18371. var boundingInfo = this.getBoundingInfo();
  18372. if (!this.subMeshes) {
  18373. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18374. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18375. }
  18376. else {
  18377. min = boundingInfo.boundingBox.minimumWorld;
  18378. max = boundingInfo.boundingBox.maximumWorld;
  18379. }
  18380. if (includeDescendants) {
  18381. var descendants = this.getDescendants(false);
  18382. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18383. var descendant = descendants_1[_i];
  18384. var childMesh = descendant;
  18385. childMesh.computeWorldMatrix(true);
  18386. //make sure we have the needed params to get mix and max
  18387. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18388. continue;
  18389. }
  18390. var childBoundingInfo = childMesh.getBoundingInfo();
  18391. var boundingBox = childBoundingInfo.boundingBox;
  18392. var minBox = boundingBox.minimumWorld;
  18393. var maxBox = boundingBox.maximumWorld;
  18394. BABYLON.Tools.CheckExtends(minBox, min, max);
  18395. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18396. }
  18397. }
  18398. return {
  18399. min: min,
  18400. max: max
  18401. };
  18402. };
  18403. /**
  18404. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18405. * Returns the AbstractMesh.
  18406. */
  18407. AbstractMesh.prototype._updateBoundingInfo = function () {
  18408. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18409. this._boundingInfo.update(this.worldMatrixFromCache);
  18410. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18411. return this;
  18412. };
  18413. /**
  18414. * Update a mesh's children BoundingInfo objects only.
  18415. * Returns the AbstractMesh.
  18416. */
  18417. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18418. if (!this.subMeshes) {
  18419. return this;
  18420. }
  18421. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18422. var subMesh = this.subMeshes[subIndex];
  18423. if (!subMesh.IsGlobal) {
  18424. subMesh.updateBoundingInfo(matrix);
  18425. }
  18426. }
  18427. return this;
  18428. };
  18429. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18430. // Bounding info
  18431. this._updateBoundingInfo();
  18432. };
  18433. /**
  18434. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18435. * A mesh is in the frustum if its bounding box intersects the frustum.
  18436. * Boolean returned.
  18437. */
  18438. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18439. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18440. };
  18441. /**
  18442. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18443. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18444. * Boolean returned.
  18445. */
  18446. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18447. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18448. ;
  18449. };
  18450. /**
  18451. * True if the mesh intersects another mesh or a SolidParticle object.
  18452. * 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)
  18453. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18454. * Returns a boolean.
  18455. */
  18456. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18457. if (precise === void 0) { precise = false; }
  18458. if (!this._boundingInfo || !mesh._boundingInfo) {
  18459. return false;
  18460. }
  18461. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18462. return true;
  18463. }
  18464. if (includeDescendants) {
  18465. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18466. var child = _a[_i];
  18467. if (child.intersectsMesh(mesh, precise, true)) {
  18468. return true;
  18469. }
  18470. }
  18471. }
  18472. return false;
  18473. };
  18474. /**
  18475. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18476. * Returns a boolean.
  18477. */
  18478. AbstractMesh.prototype.intersectsPoint = function (point) {
  18479. if (!this._boundingInfo) {
  18480. return false;
  18481. }
  18482. return this._boundingInfo.intersectsPoint(point);
  18483. };
  18484. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18485. return this.physicsImpostor;
  18486. };
  18487. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18488. if (camera === void 0) { camera = null; }
  18489. if (!camera) {
  18490. camera = this.getScene().activeCamera;
  18491. }
  18492. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18493. };
  18494. /**
  18495. * Returns the distance from the mesh to the active camera.
  18496. * Returns a float.
  18497. */
  18498. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18499. if (camera === void 0) { camera = null; }
  18500. if (!camera) {
  18501. camera = this.getScene().activeCamera;
  18502. }
  18503. return this.absolutePosition.subtract(camera.position).length();
  18504. };
  18505. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18506. if (!this.physicsImpostor) {
  18507. return this;
  18508. }
  18509. this.physicsImpostor.applyImpulse(force, contactPoint);
  18510. return this;
  18511. };
  18512. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18513. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18514. return this;
  18515. }
  18516. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18517. mainPivot: pivot1,
  18518. connectedPivot: pivot2,
  18519. nativeParams: options
  18520. });
  18521. return this;
  18522. };
  18523. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18524. // Collisions
  18525. /**
  18526. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18527. * Default `false`.
  18528. */
  18529. get: function () {
  18530. return this._checkCollisions;
  18531. },
  18532. set: function (collisionEnabled) {
  18533. this._checkCollisions = collisionEnabled;
  18534. if (this.getScene().workerCollisions) {
  18535. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18536. }
  18537. },
  18538. enumerable: true,
  18539. configurable: true
  18540. });
  18541. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18542. /**
  18543. * Gets Collider object used to compute collisions (not physics)
  18544. */
  18545. get: function () {
  18546. return this._collider;
  18547. },
  18548. enumerable: true,
  18549. configurable: true
  18550. });
  18551. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18552. var globalPosition = this.getAbsolutePosition();
  18553. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18554. if (!this._collider) {
  18555. this._collider = new BABYLON.Collider();
  18556. }
  18557. this._collider._radius = this.ellipsoid;
  18558. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18559. return this;
  18560. };
  18561. // Submeshes octree
  18562. /**
  18563. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18564. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18565. * Returns an Octree of submeshes.
  18566. */
  18567. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18568. if (maxCapacity === void 0) { maxCapacity = 64; }
  18569. if (maxDepth === void 0) { maxDepth = 2; }
  18570. if (!this._submeshesOctree) {
  18571. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18572. }
  18573. this.computeWorldMatrix(true);
  18574. var boundingInfo = this.getBoundingInfo();
  18575. // Update octree
  18576. var bbox = boundingInfo.boundingBox;
  18577. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18578. return this._submeshesOctree;
  18579. };
  18580. // Collisions
  18581. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18582. this._generatePointsArray();
  18583. if (!this._positions) {
  18584. return this;
  18585. }
  18586. // Transformation
  18587. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18588. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18589. subMesh._lastColliderWorldVertices = [];
  18590. subMesh._trianglePlanes = [];
  18591. var start = subMesh.verticesStart;
  18592. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18593. for (var i = start; i < end; i++) {
  18594. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18595. }
  18596. }
  18597. // Collide
  18598. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18599. if (collider.collisionFound) {
  18600. collider.collidedMesh = this;
  18601. }
  18602. return this;
  18603. };
  18604. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18605. var subMeshes;
  18606. var len;
  18607. // Octrees
  18608. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18609. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18610. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18611. len = intersections.length;
  18612. subMeshes = intersections.data;
  18613. }
  18614. else {
  18615. subMeshes = this.subMeshes;
  18616. len = subMeshes.length;
  18617. }
  18618. for (var index = 0; index < len; index++) {
  18619. var subMesh = subMeshes[index];
  18620. // Bounding test
  18621. if (len > 1 && !subMesh._checkCollision(collider))
  18622. continue;
  18623. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18624. }
  18625. return this;
  18626. };
  18627. AbstractMesh.prototype._checkCollision = function (collider) {
  18628. // Bounding box test
  18629. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18630. return this;
  18631. // Transformation matrix
  18632. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18633. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18634. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18635. return this;
  18636. };
  18637. // Picking
  18638. AbstractMesh.prototype._generatePointsArray = function () {
  18639. return false;
  18640. };
  18641. /**
  18642. * Checks if the passed Ray intersects with the mesh.
  18643. * Returns an object PickingInfo.
  18644. */
  18645. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18646. var pickingInfo = new BABYLON.PickingInfo();
  18647. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18648. return pickingInfo;
  18649. }
  18650. if (!this._generatePointsArray()) {
  18651. return pickingInfo;
  18652. }
  18653. var intersectInfo = null;
  18654. // Octrees
  18655. var subMeshes;
  18656. var len;
  18657. if (this._submeshesOctree && this.useOctreeForPicking) {
  18658. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18659. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18660. len = intersections.length;
  18661. subMeshes = intersections.data;
  18662. }
  18663. else {
  18664. subMeshes = this.subMeshes;
  18665. len = subMeshes.length;
  18666. }
  18667. for (var index = 0; index < len; index++) {
  18668. var subMesh = subMeshes[index];
  18669. // Bounding test
  18670. if (len > 1 && !subMesh.canIntersects(ray))
  18671. continue;
  18672. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18673. if (currentIntersectInfo) {
  18674. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18675. intersectInfo = currentIntersectInfo;
  18676. intersectInfo.subMeshId = index;
  18677. if (fastCheck) {
  18678. break;
  18679. }
  18680. }
  18681. }
  18682. }
  18683. if (intersectInfo) {
  18684. // Get picked point
  18685. var world = this.getWorldMatrix();
  18686. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18687. var direction = ray.direction.clone();
  18688. direction = direction.scale(intersectInfo.distance);
  18689. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18690. var pickedPoint = worldOrigin.add(worldDirection);
  18691. // Return result
  18692. pickingInfo.hit = true;
  18693. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18694. pickingInfo.pickedPoint = pickedPoint;
  18695. pickingInfo.pickedMesh = this;
  18696. pickingInfo.bu = intersectInfo.bu || 0;
  18697. pickingInfo.bv = intersectInfo.bv || 0;
  18698. pickingInfo.faceId = intersectInfo.faceId;
  18699. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18700. return pickingInfo;
  18701. }
  18702. return pickingInfo;
  18703. };
  18704. /**
  18705. * Clones the mesh, used by the class Mesh.
  18706. * Just returns `null` for an AbstractMesh.
  18707. */
  18708. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18709. return null;
  18710. };
  18711. /**
  18712. * Disposes all the mesh submeshes.
  18713. * Returns the AbstractMesh.
  18714. */
  18715. AbstractMesh.prototype.releaseSubMeshes = function () {
  18716. if (this.subMeshes) {
  18717. while (this.subMeshes.length) {
  18718. this.subMeshes[0].dispose();
  18719. }
  18720. }
  18721. else {
  18722. this.subMeshes = new Array();
  18723. }
  18724. return this;
  18725. };
  18726. /**
  18727. * Releases resources associated with this abstract mesh.
  18728. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18729. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18730. */
  18731. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18732. var _this = this;
  18733. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18734. var index;
  18735. // Smart Array Retainers.
  18736. this.getScene().freeActiveMeshes();
  18737. this.getScene().freeRenderingGroups();
  18738. // Action manager
  18739. if (this.actionManager !== undefined && this.actionManager !== null) {
  18740. this.actionManager.dispose();
  18741. this.actionManager = null;
  18742. }
  18743. // Skeleton
  18744. this._skeleton = null;
  18745. // Physics
  18746. if (this.physicsImpostor) {
  18747. this.physicsImpostor.dispose();
  18748. }
  18749. // Intersections in progress
  18750. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18751. var other = this._intersectionsInProgress[index];
  18752. var pos = other._intersectionsInProgress.indexOf(this);
  18753. other._intersectionsInProgress.splice(pos, 1);
  18754. }
  18755. this._intersectionsInProgress = [];
  18756. // Lights
  18757. var lights = this.getScene().lights;
  18758. lights.forEach(function (light) {
  18759. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18760. if (meshIndex !== -1) {
  18761. light.includedOnlyMeshes.splice(meshIndex, 1);
  18762. }
  18763. meshIndex = light.excludedMeshes.indexOf(_this);
  18764. if (meshIndex !== -1) {
  18765. light.excludedMeshes.splice(meshIndex, 1);
  18766. }
  18767. // Shadow generators
  18768. var generator = light.getShadowGenerator();
  18769. if (generator) {
  18770. var shadowMap = generator.getShadowMap();
  18771. if (shadowMap && shadowMap.renderList) {
  18772. meshIndex = shadowMap.renderList.indexOf(_this);
  18773. if (meshIndex !== -1) {
  18774. shadowMap.renderList.splice(meshIndex, 1);
  18775. }
  18776. }
  18777. }
  18778. });
  18779. // Edges
  18780. if (this._edgesRenderer) {
  18781. this._edgesRenderer.dispose();
  18782. this._edgesRenderer = null;
  18783. }
  18784. // SubMeshes
  18785. if (this.getClassName() !== "InstancedMesh") {
  18786. this.releaseSubMeshes();
  18787. }
  18788. // Octree
  18789. var sceneOctree = this.getScene().selectionOctree;
  18790. if (sceneOctree !== undefined && sceneOctree !== null) {
  18791. var index = sceneOctree.dynamicContent.indexOf(this);
  18792. if (index !== -1) {
  18793. sceneOctree.dynamicContent.splice(index, 1);
  18794. }
  18795. }
  18796. // Query
  18797. var engine = this.getScene().getEngine();
  18798. if (this._occlusionQuery) {
  18799. this._isOcclusionQueryInProgress = false;
  18800. engine.deleteQuery(this._occlusionQuery);
  18801. this._occlusionQuery = null;
  18802. }
  18803. // Engine
  18804. engine.wipeCaches();
  18805. // Remove from scene
  18806. this.getScene().removeMesh(this);
  18807. if (disposeMaterialAndTextures) {
  18808. if (this.material) {
  18809. this.material.dispose(false, true);
  18810. }
  18811. }
  18812. if (!doNotRecurse) {
  18813. // Particles
  18814. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18815. if (this.getScene().particleSystems[index].emitter === this) {
  18816. this.getScene().particleSystems[index].dispose();
  18817. index--;
  18818. }
  18819. }
  18820. }
  18821. // facet data
  18822. if (this._facetDataEnabled) {
  18823. this.disableFacetData();
  18824. }
  18825. this.onAfterWorldMatrixUpdateObservable.clear();
  18826. this.onCollideObservable.clear();
  18827. this.onCollisionPositionChangeObservable.clear();
  18828. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18829. };
  18830. /**
  18831. * Adds the passed mesh as a child to the current mesh.
  18832. * Returns the AbstractMesh.
  18833. */
  18834. AbstractMesh.prototype.addChild = function (mesh) {
  18835. mesh.setParent(this);
  18836. return this;
  18837. };
  18838. /**
  18839. * Removes the passed mesh from the current mesh children list.
  18840. * Returns the AbstractMesh.
  18841. */
  18842. AbstractMesh.prototype.removeChild = function (mesh) {
  18843. mesh.setParent(null);
  18844. return this;
  18845. };
  18846. // Facet data
  18847. /**
  18848. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18849. * Returns the AbstractMesh.
  18850. */
  18851. AbstractMesh.prototype._initFacetData = function () {
  18852. if (!this._facetNormals) {
  18853. this._facetNormals = new Array();
  18854. }
  18855. if (!this._facetPositions) {
  18856. this._facetPositions = new Array();
  18857. }
  18858. if (!this._facetPartitioning) {
  18859. this._facetPartitioning = new Array();
  18860. }
  18861. this._facetNb = (this.getIndices().length / 3) | 0;
  18862. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18863. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18864. for (var f = 0; f < this._facetNb; f++) {
  18865. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18866. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18867. }
  18868. this._facetDataEnabled = true;
  18869. return this;
  18870. };
  18871. /**
  18872. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18873. * This method can be called within the render loop.
  18874. * 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.
  18875. * Returns the AbstractMesh.
  18876. */
  18877. AbstractMesh.prototype.updateFacetData = function () {
  18878. if (!this._facetDataEnabled) {
  18879. this._initFacetData();
  18880. }
  18881. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18882. var indices = this.getIndices();
  18883. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18884. var bInfo = this.getBoundingInfo();
  18885. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18886. // init arrays, matrix and sort function on first call
  18887. this._facetDepthSortEnabled = true;
  18888. if (indices instanceof Uint16Array) {
  18889. this._depthSortedIndices = new Uint16Array(indices);
  18890. }
  18891. else if (indices instanceof Uint32Array) {
  18892. this._depthSortedIndices = new Uint32Array(indices);
  18893. }
  18894. else {
  18895. var needs32bits = false;
  18896. for (var i = 0; i < indices.length; i++) {
  18897. if (indices[i] > 65535) {
  18898. needs32bits = true;
  18899. break;
  18900. }
  18901. }
  18902. if (needs32bits) {
  18903. this._depthSortedIndices = new Uint32Array(indices);
  18904. }
  18905. else {
  18906. this._depthSortedIndices = new Uint16Array(indices);
  18907. }
  18908. }
  18909. this._facetDepthSortFunction = function (f1, f2) {
  18910. return (f2.sqDistance - f1.sqDistance);
  18911. };
  18912. if (!this._facetDepthSortFrom) {
  18913. var camera = this.getScene().activeCamera;
  18914. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18915. }
  18916. this._depthSortedFacets = [];
  18917. for (var f = 0; f < this._facetNb; f++) {
  18918. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18919. this._depthSortedFacets.push(depthSortedFacet);
  18920. }
  18921. this._invertedMatrix = BABYLON.Matrix.Identity();
  18922. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18923. }
  18924. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18925. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18926. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18927. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18928. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18929. this._subDiv.max = this._partitioningSubdivisions;
  18930. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18931. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18932. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18933. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18934. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18935. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18936. // set the parameters for ComputeNormals()
  18937. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18938. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18939. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18940. this._facetParameters.bInfo = bInfo;
  18941. this._facetParameters.bbSize = this._bbSize;
  18942. this._facetParameters.subDiv = this._subDiv;
  18943. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18944. this._facetParameters.depthSort = this._facetDepthSort;
  18945. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18946. this.computeWorldMatrix(true);
  18947. this._worldMatrix.invertToRef(this._invertedMatrix);
  18948. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18949. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18950. }
  18951. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18952. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18953. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18954. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18955. var l = (this._depthSortedIndices.length / 3) | 0;
  18956. for (var f = 0; f < l; f++) {
  18957. var sind = this._depthSortedFacets[f].ind;
  18958. this._depthSortedIndices[f * 3] = indices[sind];
  18959. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18960. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18961. }
  18962. this.updateIndices(this._depthSortedIndices);
  18963. }
  18964. return this;
  18965. };
  18966. /**
  18967. * Returns the facetLocalNormals array.
  18968. * The normals are expressed in the mesh local space.
  18969. */
  18970. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18971. if (!this._facetNormals) {
  18972. this.updateFacetData();
  18973. }
  18974. return this._facetNormals;
  18975. };
  18976. /**
  18977. * Returns the facetLocalPositions array.
  18978. * The facet positions are expressed in the mesh local space.
  18979. */
  18980. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18981. if (!this._facetPositions) {
  18982. this.updateFacetData();
  18983. }
  18984. return this._facetPositions;
  18985. };
  18986. /**
  18987. * Returns the facetLocalPartioning array.
  18988. */
  18989. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18990. if (!this._facetPartitioning) {
  18991. this.updateFacetData();
  18992. }
  18993. return this._facetPartitioning;
  18994. };
  18995. /**
  18996. * Returns the i-th facet position in the world system.
  18997. * This method allocates a new Vector3 per call.
  18998. */
  18999. AbstractMesh.prototype.getFacetPosition = function (i) {
  19000. var pos = BABYLON.Vector3.Zero();
  19001. this.getFacetPositionToRef(i, pos);
  19002. return pos;
  19003. };
  19004. /**
  19005. * Sets the reference Vector3 with the i-th facet position in the world system.
  19006. * Returns the AbstractMesh.
  19007. */
  19008. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19009. var localPos = (this.getFacetLocalPositions())[i];
  19010. var world = this.getWorldMatrix();
  19011. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19012. return this;
  19013. };
  19014. /**
  19015. * Returns the i-th facet normal in the world system.
  19016. * This method allocates a new Vector3 per call.
  19017. */
  19018. AbstractMesh.prototype.getFacetNormal = function (i) {
  19019. var norm = BABYLON.Vector3.Zero();
  19020. this.getFacetNormalToRef(i, norm);
  19021. return norm;
  19022. };
  19023. /**
  19024. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19025. * Returns the AbstractMesh.
  19026. */
  19027. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19028. var localNorm = (this.getFacetLocalNormals())[i];
  19029. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19030. return this;
  19031. };
  19032. /**
  19033. * 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).
  19034. */
  19035. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19036. var bInfo = this.getBoundingInfo();
  19037. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19038. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19039. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19040. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19041. return null;
  19042. }
  19043. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19044. };
  19045. /**
  19046. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19047. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19048. * 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.
  19049. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19050. * 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.
  19051. */
  19052. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19053. if (checkFace === void 0) { checkFace = false; }
  19054. if (facing === void 0) { facing = true; }
  19055. var world = this.getWorldMatrix();
  19056. var invMat = BABYLON.Tmp.Matrix[5];
  19057. world.invertToRef(invMat);
  19058. var invVect = BABYLON.Tmp.Vector3[8];
  19059. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19060. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19061. if (projected) {
  19062. // tranform the local computed projected vector to world coordinates
  19063. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19064. }
  19065. return closest;
  19066. };
  19067. /**
  19068. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19069. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19070. * 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.
  19071. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19072. * 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.
  19073. */
  19074. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19075. if (checkFace === void 0) { checkFace = false; }
  19076. if (facing === void 0) { facing = true; }
  19077. var closest = null;
  19078. var tmpx = 0.0;
  19079. var tmpy = 0.0;
  19080. var tmpz = 0.0;
  19081. var d = 0.0; // tmp dot facet normal * facet position
  19082. var t0 = 0.0;
  19083. var projx = 0.0;
  19084. var projy = 0.0;
  19085. var projz = 0.0;
  19086. // Get all the facets in the same partitioning block than (x, y, z)
  19087. var facetPositions = this.getFacetLocalPositions();
  19088. var facetNormals = this.getFacetLocalNormals();
  19089. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19090. if (!facetsInBlock) {
  19091. return null;
  19092. }
  19093. // Get the closest facet to (x, y, z)
  19094. var shortest = Number.MAX_VALUE; // init distance vars
  19095. var tmpDistance = shortest;
  19096. var fib; // current facet in the block
  19097. var norm; // current facet normal
  19098. var p0; // current facet barycenter position
  19099. // loop on all the facets in the current partitioning block
  19100. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19101. fib = facetsInBlock[idx];
  19102. norm = facetNormals[fib];
  19103. p0 = facetPositions[fib];
  19104. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19105. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19106. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19107. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19108. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19109. projx = x + norm.x * t0;
  19110. projy = y + norm.y * t0;
  19111. projz = z + norm.z * t0;
  19112. tmpx = projx - x;
  19113. tmpy = projy - y;
  19114. tmpz = projz - z;
  19115. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19116. if (tmpDistance < shortest) {
  19117. shortest = tmpDistance;
  19118. closest = fib;
  19119. if (projected) {
  19120. projected.x = projx;
  19121. projected.y = projy;
  19122. projected.z = projz;
  19123. }
  19124. }
  19125. }
  19126. }
  19127. return closest;
  19128. };
  19129. /**
  19130. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19131. */
  19132. AbstractMesh.prototype.getFacetDataParameters = function () {
  19133. return this._facetParameters;
  19134. };
  19135. /**
  19136. * Disables the feature FacetData and frees the related memory.
  19137. * Returns the AbstractMesh.
  19138. */
  19139. AbstractMesh.prototype.disableFacetData = function () {
  19140. if (this._facetDataEnabled) {
  19141. this._facetDataEnabled = false;
  19142. this._facetPositions = new Array();
  19143. this._facetNormals = new Array();
  19144. this._facetPartitioning = new Array();
  19145. this._facetParameters = null;
  19146. this._depthSortedIndices = new Uint32Array(0);
  19147. }
  19148. return this;
  19149. };
  19150. /**
  19151. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19152. * Returns the mesh.
  19153. */
  19154. AbstractMesh.prototype.updateIndices = function (indices) {
  19155. return this;
  19156. };
  19157. /**
  19158. * The mesh Geometry. Actually used by the Mesh object.
  19159. * Returns a blank geometry object.
  19160. */
  19161. /**
  19162. * Creates new normals data for the mesh.
  19163. * @param updatable.
  19164. */
  19165. AbstractMesh.prototype.createNormals = function (updatable) {
  19166. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19167. var indices = this.getIndices();
  19168. var normals;
  19169. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19170. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19171. }
  19172. else {
  19173. normals = [];
  19174. }
  19175. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19176. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19177. };
  19178. /**
  19179. * Align the mesh with a normal.
  19180. * Returns the mesh.
  19181. */
  19182. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19183. if (!upDirection) {
  19184. upDirection = BABYLON.Axis.Y;
  19185. }
  19186. var axisX = BABYLON.Tmp.Vector3[0];
  19187. var axisZ = BABYLON.Tmp.Vector3[1];
  19188. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19189. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19190. if (this.rotationQuaternion) {
  19191. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19192. }
  19193. else {
  19194. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19195. }
  19196. return this;
  19197. };
  19198. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19199. var engine = this.getEngine();
  19200. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19201. this._isOccluded = false;
  19202. return;
  19203. }
  19204. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19205. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19206. if (isOcclusionQueryAvailable) {
  19207. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19208. this._isOcclusionQueryInProgress = false;
  19209. this._occlusionInternalRetryCounter = 0;
  19210. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19211. }
  19212. else {
  19213. this._occlusionInternalRetryCounter++;
  19214. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19215. this._isOcclusionQueryInProgress = false;
  19216. this._occlusionInternalRetryCounter = 0;
  19217. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19218. // if strict continue the last state of the object.
  19219. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19220. }
  19221. else {
  19222. return;
  19223. }
  19224. }
  19225. }
  19226. var scene = this.getScene();
  19227. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19228. if (!this._occlusionQuery) {
  19229. this._occlusionQuery = engine.createQuery();
  19230. }
  19231. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19232. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19233. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19234. this._isOcclusionQueryInProgress = true;
  19235. };
  19236. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19237. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19238. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19239. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19240. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19241. return AbstractMesh;
  19242. }(BABYLON.TransformNode));
  19243. BABYLON.AbstractMesh = AbstractMesh;
  19244. })(BABYLON || (BABYLON = {}));
  19245. //# sourceMappingURL=babylon.abstractMesh.js.map
  19246. "use strict";
  19247. var BABYLON;
  19248. (function (BABYLON) {
  19249. /**
  19250. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19251. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19252. * 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.
  19253. */
  19254. var Light = /** @class */ (function (_super) {
  19255. __extends(Light, _super);
  19256. /**
  19257. * Creates a Light object in the scene.
  19258. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19259. * @param name The firendly name of the light
  19260. * @param scene The scene the light belongs too
  19261. */
  19262. function Light(name, scene) {
  19263. var _this = _super.call(this, name, scene) || this;
  19264. /**
  19265. * Diffuse gives the basic color to an object.
  19266. */
  19267. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19268. /**
  19269. * Specular produces a highlight color on an object.
  19270. * Note: This is note affecting PBR materials.
  19271. */
  19272. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19273. /**
  19274. * Strength of the light.
  19275. * Note: By default it is define in the framework own unit.
  19276. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19277. */
  19278. _this.intensity = 1.0;
  19279. /**
  19280. * Defines how far from the source the light is impacting in scene units.
  19281. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19282. */
  19283. _this.range = Number.MAX_VALUE;
  19284. /**
  19285. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19286. * of light.
  19287. */
  19288. _this._photometricScale = 1.0;
  19289. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19290. _this._radius = 0.00001;
  19291. /**
  19292. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19293. * exceeding the number allowed of the materials.
  19294. */
  19295. _this.renderPriority = 0;
  19296. /**
  19297. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19298. * the current shadow generator.
  19299. */
  19300. _this.shadowEnabled = true;
  19301. _this._excludeWithLayerMask = 0;
  19302. _this._includeOnlyWithLayerMask = 0;
  19303. _this._lightmapMode = 0;
  19304. /**
  19305. * @ignore Internal use only.
  19306. */
  19307. _this._excludedMeshesIds = new Array();
  19308. /**
  19309. * @ignore Internal use only.
  19310. */
  19311. _this._includedOnlyMeshesIds = new Array();
  19312. _this.getScene().addLight(_this);
  19313. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19314. _this._buildUniformLayout();
  19315. _this.includedOnlyMeshes = new Array();
  19316. _this.excludedMeshes = new Array();
  19317. _this._resyncMeshes();
  19318. return _this;
  19319. }
  19320. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19321. /**
  19322. * If every light affecting the material is in this lightmapMode,
  19323. * material.lightmapTexture adds or multiplies
  19324. * (depends on material.useLightmapAsShadowmap)
  19325. * after every other light calculations.
  19326. */
  19327. get: function () {
  19328. return Light._LIGHTMAP_DEFAULT;
  19329. },
  19330. enumerable: true,
  19331. configurable: true
  19332. });
  19333. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19334. /**
  19335. * material.lightmapTexture as only diffuse lighting from this light
  19336. * adds only specular lighting from this light
  19337. * adds dynamic shadows
  19338. */
  19339. get: function () {
  19340. return Light._LIGHTMAP_SPECULAR;
  19341. },
  19342. enumerable: true,
  19343. configurable: true
  19344. });
  19345. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19346. /**
  19347. * material.lightmapTexture as only lighting
  19348. * no light calculation from this light
  19349. * only adds dynamic shadows from this light
  19350. */
  19351. get: function () {
  19352. return Light._LIGHTMAP_SHADOWSONLY;
  19353. },
  19354. enumerable: true,
  19355. configurable: true
  19356. });
  19357. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19358. /**
  19359. * Each light type uses the default quantity according to its type:
  19360. * point/spot lights use luminous intensity
  19361. * directional lights use illuminance
  19362. */
  19363. get: function () {
  19364. return Light._INTENSITYMODE_AUTOMATIC;
  19365. },
  19366. enumerable: true,
  19367. configurable: true
  19368. });
  19369. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19370. /**
  19371. * lumen (lm)
  19372. */
  19373. get: function () {
  19374. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19380. /**
  19381. * candela (lm/sr)
  19382. */
  19383. get: function () {
  19384. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19390. /**
  19391. * lux (lm/m^2)
  19392. */
  19393. get: function () {
  19394. return Light._INTENSITYMODE_ILLUMINANCE;
  19395. },
  19396. enumerable: true,
  19397. configurable: true
  19398. });
  19399. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19400. /**
  19401. * nit (cd/m^2)
  19402. */
  19403. get: function () {
  19404. return Light._INTENSITYMODE_LUMINANCE;
  19405. },
  19406. enumerable: true,
  19407. configurable: true
  19408. });
  19409. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19410. /**
  19411. * Light type const id of the point light.
  19412. */
  19413. get: function () {
  19414. return Light._LIGHTTYPEID_POINTLIGHT;
  19415. },
  19416. enumerable: true,
  19417. configurable: true
  19418. });
  19419. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19420. /**
  19421. * Light type const id of the directional light.
  19422. */
  19423. get: function () {
  19424. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19425. },
  19426. enumerable: true,
  19427. configurable: true
  19428. });
  19429. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19430. /**
  19431. * Light type const id of the spot light.
  19432. */
  19433. get: function () {
  19434. return Light._LIGHTTYPEID_SPOTLIGHT;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19440. /**
  19441. * Light type const id of the hemispheric light.
  19442. */
  19443. get: function () {
  19444. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19445. },
  19446. enumerable: true,
  19447. configurable: true
  19448. });
  19449. Object.defineProperty(Light.prototype, "intensityMode", {
  19450. /**
  19451. * Gets the photometric scale used to interpret the intensity.
  19452. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19453. */
  19454. get: function () {
  19455. return this._intensityMode;
  19456. },
  19457. /**
  19458. * Sets the photometric scale used to interpret the intensity.
  19459. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19460. */
  19461. set: function (value) {
  19462. this._intensityMode = value;
  19463. this._computePhotometricScale();
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. ;
  19469. ;
  19470. Object.defineProperty(Light.prototype, "radius", {
  19471. /**
  19472. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19473. */
  19474. get: function () {
  19475. return this._radius;
  19476. },
  19477. /**
  19478. * sets the light radius used by PBR Materials to simulate soft area lights.
  19479. */
  19480. set: function (value) {
  19481. this._radius = value;
  19482. this._computePhotometricScale();
  19483. },
  19484. enumerable: true,
  19485. configurable: true
  19486. });
  19487. ;
  19488. ;
  19489. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19490. /**
  19491. * Gets the only meshes impacted by this light.
  19492. */
  19493. get: function () {
  19494. return this._includedOnlyMeshes;
  19495. },
  19496. /**
  19497. * Sets the only meshes impacted by this light.
  19498. */
  19499. set: function (value) {
  19500. this._includedOnlyMeshes = value;
  19501. this._hookArrayForIncludedOnly(value);
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19507. /**
  19508. * Gets the meshes not impacted by this light.
  19509. */
  19510. get: function () {
  19511. return this._excludedMeshes;
  19512. },
  19513. /**
  19514. * Sets the meshes not impacted by this light.
  19515. */
  19516. set: function (value) {
  19517. this._excludedMeshes = value;
  19518. this._hookArrayForExcluded(value);
  19519. },
  19520. enumerable: true,
  19521. configurable: true
  19522. });
  19523. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19524. /**
  19525. * Gets the layer id use to find what meshes are not impacted by the light.
  19526. * Inactive if 0
  19527. */
  19528. get: function () {
  19529. return this._excludeWithLayerMask;
  19530. },
  19531. /**
  19532. * Sets the layer id use to find what meshes are not impacted by the light.
  19533. * Inactive if 0
  19534. */
  19535. set: function (value) {
  19536. this._excludeWithLayerMask = value;
  19537. this._resyncMeshes();
  19538. },
  19539. enumerable: true,
  19540. configurable: true
  19541. });
  19542. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19543. /**
  19544. * Gets the layer id use to find what meshes are impacted by the light.
  19545. * Inactive if 0
  19546. */
  19547. get: function () {
  19548. return this._includeOnlyWithLayerMask;
  19549. },
  19550. /**
  19551. * Sets the layer id use to find what meshes are impacted by the light.
  19552. * Inactive if 0
  19553. */
  19554. set: function (value) {
  19555. this._includeOnlyWithLayerMask = value;
  19556. this._resyncMeshes();
  19557. },
  19558. enumerable: true,
  19559. configurable: true
  19560. });
  19561. Object.defineProperty(Light.prototype, "lightmapMode", {
  19562. /**
  19563. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19564. */
  19565. get: function () {
  19566. return this._lightmapMode;
  19567. },
  19568. /**
  19569. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19570. */
  19571. set: function (value) {
  19572. if (this._lightmapMode === value) {
  19573. return;
  19574. }
  19575. this._lightmapMode = value;
  19576. this._markMeshesAsLightDirty();
  19577. },
  19578. enumerable: true,
  19579. configurable: true
  19580. });
  19581. /**
  19582. * Returns the string "Light".
  19583. * @returns the class name
  19584. */
  19585. Light.prototype.getClassName = function () {
  19586. return "Light";
  19587. };
  19588. /**
  19589. * Converts the light information to a readable string for debug purpose.
  19590. * @param fullDetails Supports for multiple levels of logging within scene loading
  19591. * @returns the human readable light info
  19592. */
  19593. Light.prototype.toString = function (fullDetails) {
  19594. var ret = "Name: " + this.name;
  19595. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19596. if (this.animations) {
  19597. for (var i = 0; i < this.animations.length; i++) {
  19598. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19599. }
  19600. }
  19601. if (fullDetails) {
  19602. }
  19603. return ret;
  19604. };
  19605. /**
  19606. * Set the enabled state of this node.
  19607. * @param value - the new enabled state
  19608. * @see isEnabled
  19609. */
  19610. Light.prototype.setEnabled = function (value) {
  19611. _super.prototype.setEnabled.call(this, value);
  19612. this._resyncMeshes();
  19613. };
  19614. /**
  19615. * Returns the Light associated shadow generator if any.
  19616. * @return the associated shadow generator.
  19617. */
  19618. Light.prototype.getShadowGenerator = function () {
  19619. return this._shadowGenerator;
  19620. };
  19621. /**
  19622. * Returns a Vector3, the absolute light position in the World.
  19623. * @returns the world space position of the light
  19624. */
  19625. Light.prototype.getAbsolutePosition = function () {
  19626. return BABYLON.Vector3.Zero();
  19627. };
  19628. /**
  19629. * Specifies if the light will affect the passed mesh.
  19630. * @param mesh The mesh to test against the light
  19631. * @return true the mesh is affected otherwise, false.
  19632. */
  19633. Light.prototype.canAffectMesh = function (mesh) {
  19634. if (!mesh) {
  19635. return true;
  19636. }
  19637. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19638. return false;
  19639. }
  19640. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19641. return false;
  19642. }
  19643. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19644. return false;
  19645. }
  19646. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19647. return false;
  19648. }
  19649. return true;
  19650. };
  19651. /**
  19652. * Computes and Returns the light World matrix.
  19653. * @returns the world matrix
  19654. */
  19655. Light.prototype.getWorldMatrix = function () {
  19656. this._currentRenderId = this.getScene().getRenderId();
  19657. var worldMatrix = this._getWorldMatrix();
  19658. if (this.parent && this.parent.getWorldMatrix) {
  19659. if (!this._parentedWorldMatrix) {
  19660. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19661. }
  19662. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19663. this._markSyncedWithParent();
  19664. return this._parentedWorldMatrix;
  19665. }
  19666. return worldMatrix;
  19667. };
  19668. /**
  19669. * Sort function to order lights for rendering.
  19670. * @param a First Light object to compare to second.
  19671. * @param b Second Light object to compare first.
  19672. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19673. */
  19674. Light.CompareLightsPriority = function (a, b) {
  19675. //shadow-casting lights have priority over non-shadow-casting lights
  19676. //the renderPrioirty is a secondary sort criterion
  19677. if (a.shadowEnabled !== b.shadowEnabled) {
  19678. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19679. }
  19680. return b.renderPriority - a.renderPriority;
  19681. };
  19682. /**
  19683. * Releases resources associated with this node.
  19684. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19685. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19686. */
  19687. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19688. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19689. if (this._shadowGenerator) {
  19690. this._shadowGenerator.dispose();
  19691. this._shadowGenerator = null;
  19692. }
  19693. // Animations
  19694. this.getScene().stopAnimation(this);
  19695. // Remove from meshes
  19696. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19697. var mesh = _a[_i];
  19698. mesh._removeLightSource(this);
  19699. }
  19700. this._uniformBuffer.dispose();
  19701. // Remove from scene
  19702. this.getScene().removeLight(this);
  19703. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19704. };
  19705. /**
  19706. * Returns the light type ID (integer).
  19707. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19708. */
  19709. Light.prototype.getTypeID = function () {
  19710. return 0;
  19711. };
  19712. /**
  19713. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19714. * @returns the scaled intensity in intensity mode unit
  19715. */
  19716. Light.prototype.getScaledIntensity = function () {
  19717. return this._photometricScale * this.intensity;
  19718. };
  19719. /**
  19720. * Returns a new Light object, named "name", from the current one.
  19721. * @param name The name of the cloned light
  19722. * @returns the new created light
  19723. */
  19724. Light.prototype.clone = function (name) {
  19725. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19726. if (!constructor) {
  19727. return null;
  19728. }
  19729. return BABYLON.SerializationHelper.Clone(constructor, this);
  19730. };
  19731. /**
  19732. * Serializes the current light into a Serialization object.
  19733. * @returns the serialized object.
  19734. */
  19735. Light.prototype.serialize = function () {
  19736. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19737. // Type
  19738. serializationObject.type = this.getTypeID();
  19739. // Parent
  19740. if (this.parent) {
  19741. serializationObject.parentId = this.parent.id;
  19742. }
  19743. // Inclusion / exclusions
  19744. if (this.excludedMeshes.length > 0) {
  19745. serializationObject.excludedMeshesIds = [];
  19746. this.excludedMeshes.forEach(function (mesh) {
  19747. serializationObject.excludedMeshesIds.push(mesh.id);
  19748. });
  19749. }
  19750. if (this.includedOnlyMeshes.length > 0) {
  19751. serializationObject.includedOnlyMeshesIds = [];
  19752. this.includedOnlyMeshes.forEach(function (mesh) {
  19753. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19754. });
  19755. }
  19756. // Animations
  19757. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19758. serializationObject.ranges = this.serializeAnimationRanges();
  19759. return serializationObject;
  19760. };
  19761. /**
  19762. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19763. * This new light is named "name" and added to the passed scene.
  19764. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19765. * @param name The friendly name of the light
  19766. * @param scene The scene the new light will belong to
  19767. * @returns the constructor function
  19768. */
  19769. Light.GetConstructorFromName = function (type, name, scene) {
  19770. switch (type) {
  19771. case 0:
  19772. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19773. case 1:
  19774. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19775. case 2:
  19776. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19777. case 3:
  19778. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19779. }
  19780. return null;
  19781. };
  19782. /**
  19783. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19784. * @param parsedLight The JSON representation of the light
  19785. * @param scene The scene to create the parsed light in
  19786. * @returns the created light after parsing
  19787. */
  19788. Light.Parse = function (parsedLight, scene) {
  19789. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19790. if (!constructor) {
  19791. return null;
  19792. }
  19793. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19794. // Inclusion / exclusions
  19795. if (parsedLight.excludedMeshesIds) {
  19796. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19797. }
  19798. if (parsedLight.includedOnlyMeshesIds) {
  19799. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19800. }
  19801. // Parent
  19802. if (parsedLight.parentId) {
  19803. light._waitingParentId = parsedLight.parentId;
  19804. }
  19805. // Animations
  19806. if (parsedLight.animations) {
  19807. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19808. var parsedAnimation = parsedLight.animations[animationIndex];
  19809. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19810. }
  19811. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19812. }
  19813. if (parsedLight.autoAnimate) {
  19814. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19815. }
  19816. return light;
  19817. };
  19818. Light.prototype._hookArrayForExcluded = function (array) {
  19819. var _this = this;
  19820. var oldPush = array.push;
  19821. array.push = function () {
  19822. var items = [];
  19823. for (var _i = 0; _i < arguments.length; _i++) {
  19824. items[_i] = arguments[_i];
  19825. }
  19826. var result = oldPush.apply(array, items);
  19827. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19828. var item = items_1[_a];
  19829. item._resyncLighSource(_this);
  19830. }
  19831. return result;
  19832. };
  19833. var oldSplice = array.splice;
  19834. array.splice = function (index, deleteCount) {
  19835. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19836. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19837. var item = deleted_1[_i];
  19838. item._resyncLighSource(_this);
  19839. }
  19840. return deleted;
  19841. };
  19842. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19843. var item = array_1[_i];
  19844. item._resyncLighSource(this);
  19845. }
  19846. };
  19847. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19848. var _this = this;
  19849. var oldPush = array.push;
  19850. array.push = function () {
  19851. var items = [];
  19852. for (var _i = 0; _i < arguments.length; _i++) {
  19853. items[_i] = arguments[_i];
  19854. }
  19855. var result = oldPush.apply(array, items);
  19856. _this._resyncMeshes();
  19857. return result;
  19858. };
  19859. var oldSplice = array.splice;
  19860. array.splice = function (index, deleteCount) {
  19861. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19862. _this._resyncMeshes();
  19863. return deleted;
  19864. };
  19865. this._resyncMeshes();
  19866. };
  19867. Light.prototype._resyncMeshes = function () {
  19868. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19869. var mesh = _a[_i];
  19870. mesh._resyncLighSource(this);
  19871. }
  19872. };
  19873. /**
  19874. * Forces the meshes to update their light related information in their rendering used effects
  19875. * @ignore Internal Use Only
  19876. */
  19877. Light.prototype._markMeshesAsLightDirty = function () {
  19878. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19879. var mesh = _a[_i];
  19880. if (mesh._lightSources.indexOf(this) !== -1) {
  19881. mesh._markSubMeshesAsLightDirty();
  19882. }
  19883. }
  19884. };
  19885. /**
  19886. * Recomputes the cached photometric scale if needed.
  19887. */
  19888. Light.prototype._computePhotometricScale = function () {
  19889. this._photometricScale = this._getPhotometricScale();
  19890. this.getScene().resetCachedMaterial();
  19891. };
  19892. /**
  19893. * Returns the Photometric Scale according to the light type and intensity mode.
  19894. */
  19895. Light.prototype._getPhotometricScale = function () {
  19896. var photometricScale = 0.0;
  19897. var lightTypeID = this.getTypeID();
  19898. //get photometric mode
  19899. var photometricMode = this.intensityMode;
  19900. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19901. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19902. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19903. }
  19904. else {
  19905. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19906. }
  19907. }
  19908. //compute photometric scale
  19909. switch (lightTypeID) {
  19910. case Light.LIGHTTYPEID_POINTLIGHT:
  19911. case Light.LIGHTTYPEID_SPOTLIGHT:
  19912. switch (photometricMode) {
  19913. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19914. photometricScale = 1.0 / (4.0 * Math.PI);
  19915. break;
  19916. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19917. photometricScale = 1.0;
  19918. break;
  19919. case Light.INTENSITYMODE_LUMINANCE:
  19920. photometricScale = this.radius * this.radius;
  19921. break;
  19922. }
  19923. break;
  19924. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19925. switch (photometricMode) {
  19926. case Light.INTENSITYMODE_ILLUMINANCE:
  19927. photometricScale = 1.0;
  19928. break;
  19929. case Light.INTENSITYMODE_LUMINANCE:
  19930. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19931. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19932. var apexAngleRadians = this.radius;
  19933. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19934. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19935. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19936. photometricScale = solidAngle;
  19937. break;
  19938. }
  19939. break;
  19940. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19941. // No fall off in hemisperic light.
  19942. photometricScale = 1.0;
  19943. break;
  19944. }
  19945. return photometricScale;
  19946. };
  19947. /**
  19948. * Reorder the light in the scene according to their defined priority.
  19949. * @ignore Internal Use Only
  19950. */
  19951. Light.prototype._reorderLightsInScene = function () {
  19952. var scene = this.getScene();
  19953. if (this._renderPriority != 0) {
  19954. scene.requireLightSorting = true;
  19955. }
  19956. this.getScene().sortLightsByPriority();
  19957. };
  19958. //lightmapMode Consts
  19959. Light._LIGHTMAP_DEFAULT = 0;
  19960. Light._LIGHTMAP_SPECULAR = 1;
  19961. Light._LIGHTMAP_SHADOWSONLY = 2;
  19962. // Intensity Mode Consts
  19963. Light._INTENSITYMODE_AUTOMATIC = 0;
  19964. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19965. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19966. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19967. Light._INTENSITYMODE_LUMINANCE = 4;
  19968. // Light types ids const.
  19969. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19970. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19971. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19972. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19973. __decorate([
  19974. BABYLON.serializeAsColor3()
  19975. ], Light.prototype, "diffuse", void 0);
  19976. __decorate([
  19977. BABYLON.serializeAsColor3()
  19978. ], Light.prototype, "specular", void 0);
  19979. __decorate([
  19980. BABYLON.serialize()
  19981. ], Light.prototype, "intensity", void 0);
  19982. __decorate([
  19983. BABYLON.serialize()
  19984. ], Light.prototype, "range", void 0);
  19985. __decorate([
  19986. BABYLON.serialize()
  19987. ], Light.prototype, "intensityMode", null);
  19988. __decorate([
  19989. BABYLON.serialize()
  19990. ], Light.prototype, "radius", null);
  19991. __decorate([
  19992. BABYLON.serialize()
  19993. ], Light.prototype, "_renderPriority", void 0);
  19994. __decorate([
  19995. BABYLON.expandToProperty("_reorderLightsInScene")
  19996. ], Light.prototype, "renderPriority", void 0);
  19997. __decorate([
  19998. BABYLON.serialize()
  19999. ], Light.prototype, "shadowEnabled", void 0);
  20000. __decorate([
  20001. BABYLON.serialize("excludeWithLayerMask")
  20002. ], Light.prototype, "_excludeWithLayerMask", void 0);
  20003. __decorate([
  20004. BABYLON.serialize("includeOnlyWithLayerMask")
  20005. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20006. __decorate([
  20007. BABYLON.serialize("lightmapMode")
  20008. ], Light.prototype, "_lightmapMode", void 0);
  20009. return Light;
  20010. }(BABYLON.Node));
  20011. BABYLON.Light = Light;
  20012. })(BABYLON || (BABYLON = {}));
  20013. //# sourceMappingURL=babylon.light.js.map
  20014. "use strict";
  20015. var BABYLON;
  20016. (function (BABYLON) {
  20017. var Camera = /** @class */ (function (_super) {
  20018. __extends(Camera, _super);
  20019. function Camera(name, position, scene) {
  20020. var _this = _super.call(this, name, scene) || this;
  20021. /**
  20022. * The vector the camera should consider as up.
  20023. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20024. */
  20025. _this.upVector = BABYLON.Vector3.Up();
  20026. _this.orthoLeft = null;
  20027. _this.orthoRight = null;
  20028. _this.orthoBottom = null;
  20029. _this.orthoTop = null;
  20030. /**
  20031. * FOV is set in Radians. (default is 0.8)
  20032. */
  20033. _this.fov = 0.8;
  20034. _this.minZ = 1;
  20035. _this.maxZ = 10000.0;
  20036. _this.inertia = 0.9;
  20037. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20038. _this.isIntermediate = false;
  20039. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20040. /**
  20041. * Restricts the camera to viewing objects with the same layerMask.
  20042. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20043. */
  20044. _this.layerMask = 0x0FFFFFFF;
  20045. /**
  20046. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20047. */
  20048. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20049. // Camera rig members
  20050. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20051. _this._rigCameras = new Array();
  20052. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20053. _this._skipRendering = false;
  20054. _this.customRenderTargets = new Array();
  20055. // Observables
  20056. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20057. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20058. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20059. _this.onRestoreStateObservable = new BABYLON.Observable();
  20060. // Cache
  20061. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20062. _this._projectionMatrix = new BABYLON.Matrix();
  20063. _this._doNotComputeProjectionMatrix = false;
  20064. _this._postProcesses = new Array();
  20065. _this._transformMatrix = BABYLON.Matrix.Zero();
  20066. _this._activeMeshes = new BABYLON.SmartArray(256);
  20067. _this._globalPosition = BABYLON.Vector3.Zero();
  20068. _this._refreshFrustumPlanes = true;
  20069. _this.getScene().addCamera(_this);
  20070. if (!_this.getScene().activeCamera) {
  20071. _this.getScene().activeCamera = _this;
  20072. }
  20073. _this.position = position;
  20074. return _this;
  20075. }
  20076. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20077. get: function () {
  20078. return Camera._PERSPECTIVE_CAMERA;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20084. get: function () {
  20085. return Camera._ORTHOGRAPHIC_CAMERA;
  20086. },
  20087. enumerable: true,
  20088. configurable: true
  20089. });
  20090. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20091. /**
  20092. * This is the default FOV mode for perspective cameras.
  20093. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20094. *
  20095. */
  20096. get: function () {
  20097. return Camera._FOVMODE_VERTICAL_FIXED;
  20098. },
  20099. enumerable: true,
  20100. configurable: true
  20101. });
  20102. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20103. /**
  20104. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20105. *
  20106. */
  20107. get: function () {
  20108. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20109. },
  20110. enumerable: true,
  20111. configurable: true
  20112. });
  20113. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20114. get: function () {
  20115. return Camera._RIG_MODE_NONE;
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20121. get: function () {
  20122. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20123. },
  20124. enumerable: true,
  20125. configurable: true
  20126. });
  20127. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20128. get: function () {
  20129. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20130. },
  20131. enumerable: true,
  20132. configurable: true
  20133. });
  20134. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20135. get: function () {
  20136. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20137. },
  20138. enumerable: true,
  20139. configurable: true
  20140. });
  20141. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20142. get: function () {
  20143. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20144. },
  20145. enumerable: true,
  20146. configurable: true
  20147. });
  20148. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20149. get: function () {
  20150. return Camera._RIG_MODE_VR;
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20156. get: function () {
  20157. return Camera._RIG_MODE_WEBVR;
  20158. },
  20159. enumerable: true,
  20160. configurable: true
  20161. });
  20162. /**
  20163. * Store current camera state (fov, position, etc..)
  20164. */
  20165. Camera.prototype.storeState = function () {
  20166. this._stateStored = true;
  20167. this._storedFov = this.fov;
  20168. return this;
  20169. };
  20170. /**
  20171. * Restores the camera state values if it has been stored. You must call storeState() first
  20172. */
  20173. Camera.prototype._restoreStateValues = function () {
  20174. if (!this._stateStored) {
  20175. return false;
  20176. }
  20177. this.fov = this._storedFov;
  20178. return true;
  20179. };
  20180. /**
  20181. * Restored camera state. You must call storeState() first
  20182. */
  20183. Camera.prototype.restoreState = function () {
  20184. if (this._restoreStateValues()) {
  20185. this.onRestoreStateObservable.notifyObservers(this);
  20186. return true;
  20187. }
  20188. return false;
  20189. };
  20190. Camera.prototype.getClassName = function () {
  20191. return "Camera";
  20192. };
  20193. /**
  20194. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20195. */
  20196. Camera.prototype.toString = function (fullDetails) {
  20197. var ret = "Name: " + this.name;
  20198. ret += ", type: " + this.getClassName();
  20199. if (this.animations) {
  20200. for (var i = 0; i < this.animations.length; i++) {
  20201. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20202. }
  20203. }
  20204. if (fullDetails) {
  20205. }
  20206. return ret;
  20207. };
  20208. Object.defineProperty(Camera.prototype, "globalPosition", {
  20209. get: function () {
  20210. return this._globalPosition;
  20211. },
  20212. enumerable: true,
  20213. configurable: true
  20214. });
  20215. Camera.prototype.getActiveMeshes = function () {
  20216. return this._activeMeshes;
  20217. };
  20218. Camera.prototype.isActiveMesh = function (mesh) {
  20219. return (this._activeMeshes.indexOf(mesh) !== -1);
  20220. };
  20221. //Cache
  20222. Camera.prototype._initCache = function () {
  20223. _super.prototype._initCache.call(this);
  20224. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20225. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20226. this._cache.mode = undefined;
  20227. this._cache.minZ = undefined;
  20228. this._cache.maxZ = undefined;
  20229. this._cache.fov = undefined;
  20230. this._cache.fovMode = undefined;
  20231. this._cache.aspectRatio = undefined;
  20232. this._cache.orthoLeft = undefined;
  20233. this._cache.orthoRight = undefined;
  20234. this._cache.orthoBottom = undefined;
  20235. this._cache.orthoTop = undefined;
  20236. this._cache.renderWidth = undefined;
  20237. this._cache.renderHeight = undefined;
  20238. };
  20239. Camera.prototype._updateCache = function (ignoreParentClass) {
  20240. if (!ignoreParentClass) {
  20241. _super.prototype._updateCache.call(this);
  20242. }
  20243. this._cache.position.copyFrom(this.position);
  20244. this._cache.upVector.copyFrom(this.upVector);
  20245. };
  20246. // Synchronized
  20247. Camera.prototype._isSynchronized = function () {
  20248. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20249. };
  20250. Camera.prototype._isSynchronizedViewMatrix = function () {
  20251. if (!_super.prototype._isSynchronized.call(this))
  20252. return false;
  20253. return this._cache.position.equals(this.position)
  20254. && this._cache.upVector.equals(this.upVector)
  20255. && this.isSynchronizedWithParent();
  20256. };
  20257. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20258. var check = this._cache.mode === this.mode
  20259. && this._cache.minZ === this.minZ
  20260. && this._cache.maxZ === this.maxZ;
  20261. if (!check) {
  20262. return false;
  20263. }
  20264. var engine = this.getEngine();
  20265. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20266. check = this._cache.fov === this.fov
  20267. && this._cache.fovMode === this.fovMode
  20268. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20269. }
  20270. else {
  20271. check = this._cache.orthoLeft === this.orthoLeft
  20272. && this._cache.orthoRight === this.orthoRight
  20273. && this._cache.orthoBottom === this.orthoBottom
  20274. && this._cache.orthoTop === this.orthoTop
  20275. && this._cache.renderWidth === engine.getRenderWidth()
  20276. && this._cache.renderHeight === engine.getRenderHeight();
  20277. }
  20278. return check;
  20279. };
  20280. // Controls
  20281. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20282. };
  20283. Camera.prototype.detachControl = function (element) {
  20284. };
  20285. Camera.prototype.update = function () {
  20286. this._checkInputs();
  20287. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20288. this._updateRigCameras();
  20289. }
  20290. };
  20291. Camera.prototype._checkInputs = function () {
  20292. this.onAfterCheckInputsObservable.notifyObservers(this);
  20293. };
  20294. Object.defineProperty(Camera.prototype, "rigCameras", {
  20295. get: function () {
  20296. return this._rigCameras;
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20302. get: function () {
  20303. return this._rigPostProcess;
  20304. },
  20305. enumerable: true,
  20306. configurable: true
  20307. });
  20308. /**
  20309. * Internal, gets the first post proces.
  20310. * @returns the first post process to be run on this camera.
  20311. */
  20312. Camera.prototype._getFirstPostProcess = function () {
  20313. for (var pp in this._postProcesses) {
  20314. if (this._postProcesses[pp] !== null) {
  20315. return this._postProcesses[pp];
  20316. }
  20317. }
  20318. return null;
  20319. };
  20320. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20321. // invalidate framebuffer
  20322. var firstPostProcess = this._getFirstPostProcess();
  20323. if (firstPostProcess) {
  20324. firstPostProcess.markTextureDirty();
  20325. }
  20326. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20327. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20328. var cam = this._rigCameras[i];
  20329. var rigPostProcess = cam._rigPostProcess;
  20330. // for VR rig, there does not have to be a post process
  20331. if (rigPostProcess) {
  20332. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20333. if (isPass) {
  20334. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20335. cam.isIntermediate = this._postProcesses.length === 0;
  20336. }
  20337. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20338. rigPostProcess.markTextureDirty();
  20339. }
  20340. else {
  20341. cam._postProcesses = this._postProcesses.slice(0);
  20342. }
  20343. }
  20344. };
  20345. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20346. if (insertAt === void 0) { insertAt = null; }
  20347. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20348. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20349. return 0;
  20350. }
  20351. if (insertAt == null || insertAt < 0) {
  20352. this._postProcesses.push(postProcess);
  20353. }
  20354. else if (this._postProcesses[insertAt] === null) {
  20355. this._postProcesses[insertAt] = postProcess;
  20356. }
  20357. else {
  20358. this._postProcesses.splice(insertAt, 0, postProcess);
  20359. }
  20360. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20361. return this._postProcesses.indexOf(postProcess);
  20362. };
  20363. Camera.prototype.detachPostProcess = function (postProcess) {
  20364. var idx = this._postProcesses.indexOf(postProcess);
  20365. if (idx !== -1) {
  20366. this._postProcesses[idx] = null;
  20367. }
  20368. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20369. };
  20370. Camera.prototype.getWorldMatrix = function () {
  20371. if (!this._worldMatrix) {
  20372. this._worldMatrix = BABYLON.Matrix.Identity();
  20373. }
  20374. var viewMatrix = this.getViewMatrix();
  20375. viewMatrix.invertToRef(this._worldMatrix);
  20376. return this._worldMatrix;
  20377. };
  20378. Camera.prototype._getViewMatrix = function () {
  20379. return BABYLON.Matrix.Identity();
  20380. };
  20381. Camera.prototype.getViewMatrix = function (force) {
  20382. if (!force && this._isSynchronizedViewMatrix()) {
  20383. return this._computedViewMatrix;
  20384. }
  20385. this.updateCache();
  20386. this._computedViewMatrix = this._getViewMatrix();
  20387. this._currentRenderId = this.getScene().getRenderId();
  20388. this._refreshFrustumPlanes = true;
  20389. if (!this.parent || !this.parent.getWorldMatrix) {
  20390. this._globalPosition.copyFrom(this.position);
  20391. }
  20392. else {
  20393. if (!this._worldMatrix) {
  20394. this._worldMatrix = BABYLON.Matrix.Identity();
  20395. }
  20396. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20397. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20398. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20399. this._computedViewMatrix.invert();
  20400. this._markSyncedWithParent();
  20401. }
  20402. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20403. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20404. }
  20405. this.onViewMatrixChangedObservable.notifyObservers(this);
  20406. return this._computedViewMatrix;
  20407. };
  20408. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20409. this._doNotComputeProjectionMatrix = true;
  20410. if (projection !== undefined) {
  20411. this._projectionMatrix = projection;
  20412. }
  20413. };
  20414. ;
  20415. Camera.prototype.unfreezeProjectionMatrix = function () {
  20416. this._doNotComputeProjectionMatrix = false;
  20417. };
  20418. ;
  20419. Camera.prototype.getProjectionMatrix = function (force) {
  20420. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20421. return this._projectionMatrix;
  20422. }
  20423. // Cache
  20424. this._cache.mode = this.mode;
  20425. this._cache.minZ = this.minZ;
  20426. this._cache.maxZ = this.maxZ;
  20427. // Matrix
  20428. this._refreshFrustumPlanes = true;
  20429. var engine = this.getEngine();
  20430. var scene = this.getScene();
  20431. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20432. this._cache.fov = this.fov;
  20433. this._cache.fovMode = this.fovMode;
  20434. this._cache.aspectRatio = engine.getAspectRatio(this);
  20435. if (this.minZ <= 0) {
  20436. this.minZ = 0.1;
  20437. }
  20438. if (scene.useRightHandedSystem) {
  20439. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20440. }
  20441. else {
  20442. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20443. }
  20444. }
  20445. else {
  20446. var halfWidth = engine.getRenderWidth() / 2.0;
  20447. var halfHeight = engine.getRenderHeight() / 2.0;
  20448. if (scene.useRightHandedSystem) {
  20449. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20450. }
  20451. else {
  20452. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20453. }
  20454. this._cache.orthoLeft = this.orthoLeft;
  20455. this._cache.orthoRight = this.orthoRight;
  20456. this._cache.orthoBottom = this.orthoBottom;
  20457. this._cache.orthoTop = this.orthoTop;
  20458. this._cache.renderWidth = engine.getRenderWidth();
  20459. this._cache.renderHeight = engine.getRenderHeight();
  20460. }
  20461. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20462. return this._projectionMatrix;
  20463. };
  20464. Camera.prototype.getTranformationMatrix = function () {
  20465. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20466. return this._transformMatrix;
  20467. };
  20468. Camera.prototype.updateFrustumPlanes = function () {
  20469. if (!this._refreshFrustumPlanes) {
  20470. return;
  20471. }
  20472. this.getTranformationMatrix();
  20473. if (!this._frustumPlanes) {
  20474. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20475. }
  20476. else {
  20477. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20478. }
  20479. this._refreshFrustumPlanes = false;
  20480. };
  20481. Camera.prototype.isInFrustum = function (target) {
  20482. this.updateFrustumPlanes();
  20483. return target.isInFrustum(this._frustumPlanes);
  20484. };
  20485. Camera.prototype.isCompletelyInFrustum = function (target) {
  20486. this.updateFrustumPlanes();
  20487. return target.isCompletelyInFrustum(this._frustumPlanes);
  20488. };
  20489. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20490. if (length === void 0) { length = 100; }
  20491. if (!transform) {
  20492. transform = this.getWorldMatrix();
  20493. }
  20494. if (!origin) {
  20495. origin = this.position;
  20496. }
  20497. var forward = new BABYLON.Vector3(0, 0, 1);
  20498. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20499. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20500. return new BABYLON.Ray(origin, direction, length);
  20501. };
  20502. /**
  20503. * Releases resources associated with this node.
  20504. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20505. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20506. */
  20507. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20508. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20509. // Observables
  20510. this.onViewMatrixChangedObservable.clear();
  20511. this.onProjectionMatrixChangedObservable.clear();
  20512. this.onAfterCheckInputsObservable.clear();
  20513. this.onRestoreStateObservable.clear();
  20514. // Inputs
  20515. if (this.inputs) {
  20516. this.inputs.clear();
  20517. }
  20518. // Animations
  20519. this.getScene().stopAnimation(this);
  20520. // Remove from scene
  20521. this.getScene().removeCamera(this);
  20522. while (this._rigCameras.length > 0) {
  20523. var camera = this._rigCameras.pop();
  20524. if (camera) {
  20525. camera.dispose();
  20526. }
  20527. }
  20528. // Postprocesses
  20529. if (this._rigPostProcess) {
  20530. this._rigPostProcess.dispose(this);
  20531. this._rigPostProcess = null;
  20532. this._postProcesses = [];
  20533. }
  20534. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20535. this._rigPostProcess = null;
  20536. this._postProcesses = [];
  20537. }
  20538. else {
  20539. var i = this._postProcesses.length;
  20540. while (--i >= 0) {
  20541. var postProcess = this._postProcesses[i];
  20542. if (postProcess) {
  20543. postProcess.dispose(this);
  20544. }
  20545. }
  20546. }
  20547. // Render targets
  20548. var i = this.customRenderTargets.length;
  20549. while (--i >= 0) {
  20550. this.customRenderTargets[i].dispose();
  20551. }
  20552. this.customRenderTargets = [];
  20553. // Active Meshes
  20554. this._activeMeshes.dispose();
  20555. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20556. };
  20557. Object.defineProperty(Camera.prototype, "leftCamera", {
  20558. // ---- Camera rigs section ----
  20559. get: function () {
  20560. if (this._rigCameras.length < 1) {
  20561. return null;
  20562. }
  20563. return this._rigCameras[0];
  20564. },
  20565. enumerable: true,
  20566. configurable: true
  20567. });
  20568. Object.defineProperty(Camera.prototype, "rightCamera", {
  20569. get: function () {
  20570. if (this._rigCameras.length < 2) {
  20571. return null;
  20572. }
  20573. return this._rigCameras[1];
  20574. },
  20575. enumerable: true,
  20576. configurable: true
  20577. });
  20578. Camera.prototype.getLeftTarget = function () {
  20579. if (this._rigCameras.length < 1) {
  20580. return null;
  20581. }
  20582. return this._rigCameras[0].getTarget();
  20583. };
  20584. Camera.prototype.getRightTarget = function () {
  20585. if (this._rigCameras.length < 2) {
  20586. return null;
  20587. }
  20588. return this._rigCameras[1].getTarget();
  20589. };
  20590. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20591. if (this.cameraRigMode === mode) {
  20592. return;
  20593. }
  20594. while (this._rigCameras.length > 0) {
  20595. var camera = this._rigCameras.pop();
  20596. if (camera) {
  20597. camera.dispose();
  20598. }
  20599. }
  20600. this.cameraRigMode = mode;
  20601. this._cameraRigParams = {};
  20602. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20603. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20604. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20605. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20606. // create the rig cameras, unless none
  20607. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20608. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20609. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20610. if (leftCamera && rightCamera) {
  20611. this._rigCameras.push(leftCamera);
  20612. this._rigCameras.push(rightCamera);
  20613. }
  20614. }
  20615. switch (this.cameraRigMode) {
  20616. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20617. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20618. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20619. break;
  20620. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20621. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20622. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20623. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20624. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20625. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20626. break;
  20627. case Camera.RIG_MODE_VR:
  20628. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20629. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20630. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20631. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20632. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20633. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20634. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20635. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20636. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20637. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20638. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20639. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20640. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20641. if (metrics.compensateDistortion) {
  20642. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20643. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20644. }
  20645. break;
  20646. case Camera.RIG_MODE_WEBVR:
  20647. if (rigParams.vrDisplay) {
  20648. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20649. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20650. //Left eye
  20651. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20652. this._rigCameras[0].setCameraRigParameter("left", true);
  20653. //leaving this for future reference
  20654. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20655. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20656. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20657. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20658. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20659. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20660. this._rigCameras[0].parent = this;
  20661. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20662. //Right eye
  20663. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20664. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20665. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20666. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20667. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20668. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20669. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20670. this._rigCameras[1].parent = this;
  20671. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20672. if (Camera.UseAlternateWebVRRendering) {
  20673. this._rigCameras[1]._skipRendering = true;
  20674. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20675. }
  20676. }
  20677. break;
  20678. }
  20679. this._cascadePostProcessesToRigCams();
  20680. this.update();
  20681. };
  20682. Camera.prototype._getVRProjectionMatrix = function () {
  20683. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20684. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20685. return this._projectionMatrix;
  20686. };
  20687. Camera.prototype._updateCameraRotationMatrix = function () {
  20688. //Here for WebVR
  20689. };
  20690. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20691. //Here for WebVR
  20692. };
  20693. /**
  20694. * This function MUST be overwritten by the different WebVR cameras available.
  20695. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20696. */
  20697. Camera.prototype._getWebVRProjectionMatrix = function () {
  20698. return BABYLON.Matrix.Identity();
  20699. };
  20700. /**
  20701. * This function MUST be overwritten by the different WebVR cameras available.
  20702. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20703. */
  20704. Camera.prototype._getWebVRViewMatrix = function () {
  20705. return BABYLON.Matrix.Identity();
  20706. };
  20707. Camera.prototype.setCameraRigParameter = function (name, value) {
  20708. if (!this._cameraRigParams) {
  20709. this._cameraRigParams = {};
  20710. }
  20711. this._cameraRigParams[name] = value;
  20712. //provisionnally:
  20713. if (name === "interaxialDistance") {
  20714. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20715. }
  20716. };
  20717. /**
  20718. * needs to be overridden by children so sub has required properties to be copied
  20719. */
  20720. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20721. return null;
  20722. };
  20723. /**
  20724. * May need to be overridden by children
  20725. */
  20726. Camera.prototype._updateRigCameras = function () {
  20727. for (var i = 0; i < this._rigCameras.length; i++) {
  20728. this._rigCameras[i].minZ = this.minZ;
  20729. this._rigCameras[i].maxZ = this.maxZ;
  20730. this._rigCameras[i].fov = this.fov;
  20731. }
  20732. // only update viewport when ANAGLYPH
  20733. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20734. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20735. }
  20736. };
  20737. Camera.prototype._setupInputs = function () {
  20738. };
  20739. Camera.prototype.serialize = function () {
  20740. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20741. // Type
  20742. serializationObject.type = this.getClassName();
  20743. // Parent
  20744. if (this.parent) {
  20745. serializationObject.parentId = this.parent.id;
  20746. }
  20747. if (this.inputs) {
  20748. this.inputs.serialize(serializationObject);
  20749. }
  20750. // Animations
  20751. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20752. serializationObject.ranges = this.serializeAnimationRanges();
  20753. return serializationObject;
  20754. };
  20755. Camera.prototype.clone = function (name) {
  20756. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20757. };
  20758. Camera.prototype.getDirection = function (localAxis) {
  20759. var result = BABYLON.Vector3.Zero();
  20760. this.getDirectionToRef(localAxis, result);
  20761. return result;
  20762. };
  20763. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20764. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20765. };
  20766. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20767. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20768. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20769. switch (type) {
  20770. case "ArcRotateCamera":
  20771. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20772. case "DeviceOrientationCamera":
  20773. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20774. case "FollowCamera":
  20775. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20776. case "ArcFollowCamera":
  20777. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20778. case "GamepadCamera":
  20779. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20780. case "TouchCamera":
  20781. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20782. case "VirtualJoysticksCamera":
  20783. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20784. case "WebVRFreeCamera":
  20785. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20786. case "WebVRGamepadCamera":
  20787. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20788. case "VRDeviceOrientationFreeCamera":
  20789. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20790. case "VRDeviceOrientationGamepadCamera":
  20791. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20792. case "AnaglyphArcRotateCamera":
  20793. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20794. case "AnaglyphFreeCamera":
  20795. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20796. case "AnaglyphGamepadCamera":
  20797. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20798. case "AnaglyphUniversalCamera":
  20799. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20800. case "StereoscopicArcRotateCamera":
  20801. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20802. case "StereoscopicFreeCamera":
  20803. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20804. case "StereoscopicGamepadCamera":
  20805. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20806. case "StereoscopicUniversalCamera":
  20807. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20808. case "FreeCamera":// Forcing Universal here
  20809. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20810. default:// Universal Camera is the default value
  20811. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20812. }
  20813. };
  20814. Camera.prototype.computeWorldMatrix = function () {
  20815. return this.getWorldMatrix();
  20816. };
  20817. Camera.Parse = function (parsedCamera, scene) {
  20818. var type = parsedCamera.type;
  20819. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20820. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20821. // Parent
  20822. if (parsedCamera.parentId) {
  20823. camera._waitingParentId = parsedCamera.parentId;
  20824. }
  20825. //If camera has an input manager, let it parse inputs settings
  20826. if (camera.inputs) {
  20827. camera.inputs.parse(parsedCamera);
  20828. camera._setupInputs();
  20829. }
  20830. if (camera.setPosition) {
  20831. camera.position.copyFromFloats(0, 0, 0);
  20832. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20833. }
  20834. // Target
  20835. if (parsedCamera.target) {
  20836. if (camera.setTarget) {
  20837. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20838. }
  20839. }
  20840. // Apply 3d rig, when found
  20841. if (parsedCamera.cameraRigMode) {
  20842. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20843. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20844. }
  20845. // Animations
  20846. if (parsedCamera.animations) {
  20847. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20848. var parsedAnimation = parsedCamera.animations[animationIndex];
  20849. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20850. }
  20851. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20852. }
  20853. if (parsedCamera.autoAnimate) {
  20854. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20855. }
  20856. return camera;
  20857. };
  20858. // Statics
  20859. Camera._PERSPECTIVE_CAMERA = 0;
  20860. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20861. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20862. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20863. Camera._RIG_MODE_NONE = 0;
  20864. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20865. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20866. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20867. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20868. Camera._RIG_MODE_VR = 20;
  20869. Camera._RIG_MODE_WEBVR = 21;
  20870. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20871. Camera.UseAlternateWebVRRendering = false;
  20872. __decorate([
  20873. BABYLON.serializeAsVector3()
  20874. ], Camera.prototype, "position", void 0);
  20875. __decorate([
  20876. BABYLON.serializeAsVector3()
  20877. ], Camera.prototype, "upVector", void 0);
  20878. __decorate([
  20879. BABYLON.serialize()
  20880. ], Camera.prototype, "orthoLeft", void 0);
  20881. __decorate([
  20882. BABYLON.serialize()
  20883. ], Camera.prototype, "orthoRight", void 0);
  20884. __decorate([
  20885. BABYLON.serialize()
  20886. ], Camera.prototype, "orthoBottom", void 0);
  20887. __decorate([
  20888. BABYLON.serialize()
  20889. ], Camera.prototype, "orthoTop", void 0);
  20890. __decorate([
  20891. BABYLON.serialize()
  20892. ], Camera.prototype, "fov", void 0);
  20893. __decorate([
  20894. BABYLON.serialize()
  20895. ], Camera.prototype, "minZ", void 0);
  20896. __decorate([
  20897. BABYLON.serialize()
  20898. ], Camera.prototype, "maxZ", void 0);
  20899. __decorate([
  20900. BABYLON.serialize()
  20901. ], Camera.prototype, "inertia", void 0);
  20902. __decorate([
  20903. BABYLON.serialize()
  20904. ], Camera.prototype, "mode", void 0);
  20905. __decorate([
  20906. BABYLON.serialize()
  20907. ], Camera.prototype, "layerMask", void 0);
  20908. __decorate([
  20909. BABYLON.serialize()
  20910. ], Camera.prototype, "fovMode", void 0);
  20911. __decorate([
  20912. BABYLON.serialize()
  20913. ], Camera.prototype, "cameraRigMode", void 0);
  20914. __decorate([
  20915. BABYLON.serialize()
  20916. ], Camera.prototype, "interaxialDistance", void 0);
  20917. __decorate([
  20918. BABYLON.serialize()
  20919. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20920. return Camera;
  20921. }(BABYLON.Node));
  20922. BABYLON.Camera = Camera;
  20923. })(BABYLON || (BABYLON = {}));
  20924. //# sourceMappingURL=babylon.camera.js.map
  20925. "use strict";
  20926. var BABYLON;
  20927. (function (BABYLON) {
  20928. var RenderingManager = /** @class */ (function () {
  20929. function RenderingManager(scene) {
  20930. this._renderingGroups = new Array();
  20931. this._autoClearDepthStencil = {};
  20932. this._customOpaqueSortCompareFn = {};
  20933. this._customAlphaTestSortCompareFn = {};
  20934. this._customTransparentSortCompareFn = {};
  20935. this._renderinGroupInfo = null;
  20936. this._scene = scene;
  20937. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20938. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20939. }
  20940. }
  20941. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20942. if (depth === void 0) { depth = true; }
  20943. if (stencil === void 0) { stencil = true; }
  20944. if (this._depthStencilBufferAlreadyCleaned) {
  20945. return;
  20946. }
  20947. this._scene.getEngine().clear(null, false, depth, stencil);
  20948. this._depthStencilBufferAlreadyCleaned = true;
  20949. };
  20950. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20951. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20952. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20953. var info = null;
  20954. if (observable) {
  20955. if (!this._renderinGroupInfo) {
  20956. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20957. }
  20958. info = this._renderinGroupInfo;
  20959. info.scene = this._scene;
  20960. info.camera = this._scene.activeCamera;
  20961. }
  20962. // Dispatch sprites
  20963. if (renderSprites) {
  20964. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20965. var manager = this._scene.spriteManagers[index];
  20966. this.dispatchSprites(manager);
  20967. }
  20968. }
  20969. // Render
  20970. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20971. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20972. var renderingGroup = this._renderingGroups[index];
  20973. if (!renderingGroup && !observable)
  20974. continue;
  20975. var renderingGroupMask = 0;
  20976. // Fire PRECLEAR stage
  20977. if (observable && info) {
  20978. renderingGroupMask = Math.pow(2, index);
  20979. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20980. info.renderingGroupId = index;
  20981. observable.notifyObservers(info, renderingGroupMask);
  20982. }
  20983. // Clear depth/stencil if needed
  20984. if (RenderingManager.AUTOCLEAR) {
  20985. var autoClear = this._autoClearDepthStencil[index];
  20986. if (autoClear && autoClear.autoClear) {
  20987. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20988. }
  20989. }
  20990. if (observable && info) {
  20991. // Fire PREOPAQUE stage
  20992. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20993. observable.notifyObservers(info, renderingGroupMask);
  20994. // Fire PRETRANSPARENT stage
  20995. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20996. observable.notifyObservers(info, renderingGroupMask);
  20997. }
  20998. if (renderingGroup)
  20999. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21000. // Fire POSTTRANSPARENT stage
  21001. if (observable && info) {
  21002. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21003. observable.notifyObservers(info, renderingGroupMask);
  21004. }
  21005. }
  21006. };
  21007. RenderingManager.prototype.reset = function () {
  21008. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21009. var renderingGroup = this._renderingGroups[index];
  21010. if (renderingGroup) {
  21011. renderingGroup.prepare();
  21012. }
  21013. }
  21014. };
  21015. RenderingManager.prototype.dispose = function () {
  21016. this.freeRenderingGroups();
  21017. this._renderingGroups.length = 0;
  21018. };
  21019. /**
  21020. * Clear the info related to rendering groups preventing retention points during dispose.
  21021. */
  21022. RenderingManager.prototype.freeRenderingGroups = function () {
  21023. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21024. var renderingGroup = this._renderingGroups[index];
  21025. if (renderingGroup) {
  21026. renderingGroup.dispose();
  21027. }
  21028. }
  21029. };
  21030. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21031. if (this._renderingGroups[renderingGroupId] === undefined) {
  21032. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21033. }
  21034. };
  21035. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21036. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21037. this._prepareRenderingGroup(renderingGroupId);
  21038. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21039. };
  21040. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21041. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21042. this._prepareRenderingGroup(renderingGroupId);
  21043. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21044. };
  21045. /**
  21046. * @param subMesh The submesh to dispatch
  21047. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21048. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21049. */
  21050. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21051. if (mesh === undefined) {
  21052. mesh = subMesh.getMesh();
  21053. }
  21054. var renderingGroupId = mesh.renderingGroupId || 0;
  21055. this._prepareRenderingGroup(renderingGroupId);
  21056. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21057. };
  21058. /**
  21059. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21060. * This allowed control for front to back rendering or reversly depending of the special needs.
  21061. *
  21062. * @param renderingGroupId The rendering group id corresponding to its index
  21063. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21064. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21065. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21066. */
  21067. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21068. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21069. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21070. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21071. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21072. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21073. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21074. if (this._renderingGroups[renderingGroupId]) {
  21075. var group = this._renderingGroups[renderingGroupId];
  21076. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21077. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21078. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21079. }
  21080. };
  21081. /**
  21082. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21083. *
  21084. * @param renderingGroupId The rendering group id corresponding to its index
  21085. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21086. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21087. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21088. */
  21089. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21090. if (depth === void 0) { depth = true; }
  21091. if (stencil === void 0) { stencil = true; }
  21092. this._autoClearDepthStencil[renderingGroupId] = {
  21093. autoClear: autoClearDepthStencil,
  21094. depth: depth,
  21095. stencil: stencil
  21096. };
  21097. };
  21098. /**
  21099. * The max id used for rendering groups (not included)
  21100. */
  21101. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21102. /**
  21103. * The min id used for rendering groups (included)
  21104. */
  21105. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21106. /**
  21107. * Used to globally prevent autoclearing scenes.
  21108. */
  21109. RenderingManager.AUTOCLEAR = true;
  21110. return RenderingManager;
  21111. }());
  21112. BABYLON.RenderingManager = RenderingManager;
  21113. })(BABYLON || (BABYLON = {}));
  21114. //# sourceMappingURL=babylon.renderingManager.js.map
  21115. "use strict";
  21116. var BABYLON;
  21117. (function (BABYLON) {
  21118. var RenderingGroup = /** @class */ (function () {
  21119. /**
  21120. * Creates a new rendering group.
  21121. * @param index The rendering group index
  21122. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21123. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21124. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21125. */
  21126. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21127. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21128. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21129. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21130. this.index = index;
  21131. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21132. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21133. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21134. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21135. this._particleSystems = new BABYLON.SmartArray(256);
  21136. this._spriteManagers = new BABYLON.SmartArray(256);
  21137. this._edgesRenderers = new BABYLON.SmartArray(16);
  21138. this._scene = scene;
  21139. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21140. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21141. this.transparentSortCompareFn = transparentSortCompareFn;
  21142. }
  21143. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21144. /**
  21145. * Set the opaque sort comparison function.
  21146. * If null the sub meshes will be render in the order they were created
  21147. */
  21148. set: function (value) {
  21149. this._opaqueSortCompareFn = value;
  21150. if (value) {
  21151. this._renderOpaque = this.renderOpaqueSorted;
  21152. }
  21153. else {
  21154. this._renderOpaque = RenderingGroup.renderUnsorted;
  21155. }
  21156. },
  21157. enumerable: true,
  21158. configurable: true
  21159. });
  21160. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21161. /**
  21162. * Set the alpha test sort comparison function.
  21163. * If null the sub meshes will be render in the order they were created
  21164. */
  21165. set: function (value) {
  21166. this._alphaTestSortCompareFn = value;
  21167. if (value) {
  21168. this._renderAlphaTest = this.renderAlphaTestSorted;
  21169. }
  21170. else {
  21171. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21172. }
  21173. },
  21174. enumerable: true,
  21175. configurable: true
  21176. });
  21177. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21178. /**
  21179. * Set the transparent sort comparison function.
  21180. * If null the sub meshes will be render in the order they were created
  21181. */
  21182. set: function (value) {
  21183. if (value) {
  21184. this._transparentSortCompareFn = value;
  21185. }
  21186. else {
  21187. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21188. }
  21189. this._renderTransparent = this.renderTransparentSorted;
  21190. },
  21191. enumerable: true,
  21192. configurable: true
  21193. });
  21194. /**
  21195. * Render all the sub meshes contained in the group.
  21196. * @param customRenderFunction Used to override the default render behaviour of the group.
  21197. * @returns true if rendered some submeshes.
  21198. */
  21199. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21200. if (customRenderFunction) {
  21201. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21202. return;
  21203. }
  21204. var engine = this._scene.getEngine();
  21205. // Depth only
  21206. if (this._depthOnlySubMeshes.length !== 0) {
  21207. engine.setColorWrite(false);
  21208. this._renderAlphaTest(this._depthOnlySubMeshes);
  21209. engine.setColorWrite(true);
  21210. }
  21211. // Opaque
  21212. if (this._opaqueSubMeshes.length !== 0) {
  21213. this._renderOpaque(this._opaqueSubMeshes);
  21214. }
  21215. // Alpha test
  21216. if (this._alphaTestSubMeshes.length !== 0) {
  21217. this._renderAlphaTest(this._alphaTestSubMeshes);
  21218. }
  21219. var stencilState = engine.getStencilBuffer();
  21220. engine.setStencilBuffer(false);
  21221. // Sprites
  21222. if (renderSprites) {
  21223. this._renderSprites();
  21224. }
  21225. // Particles
  21226. if (renderParticles) {
  21227. this._renderParticles(activeMeshes);
  21228. }
  21229. if (this.onBeforeTransparentRendering) {
  21230. this.onBeforeTransparentRendering();
  21231. }
  21232. // Transparent
  21233. if (this._transparentSubMeshes.length !== 0) {
  21234. this._renderTransparent(this._transparentSubMeshes);
  21235. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21236. }
  21237. // Set back stencil to false in case it changes before the edge renderer.
  21238. engine.setStencilBuffer(false);
  21239. // Edges
  21240. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21241. this._edgesRenderers.data[edgesRendererIndex].render();
  21242. }
  21243. // Restore Stencil state.
  21244. engine.setStencilBuffer(stencilState);
  21245. };
  21246. /**
  21247. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21248. * @param subMeshes The submeshes to render
  21249. */
  21250. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21251. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21252. };
  21253. /**
  21254. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21255. * @param subMeshes The submeshes to render
  21256. */
  21257. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21258. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21259. };
  21260. /**
  21261. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21262. * @param subMeshes The submeshes to render
  21263. */
  21264. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21265. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21266. };
  21267. /**
  21268. * Renders the submeshes in a specified order.
  21269. * @param subMeshes The submeshes to sort before render
  21270. * @param sortCompareFn The comparison function use to sort
  21271. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21272. * @param transparent Specifies to activate blending if true
  21273. */
  21274. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21275. var subIndex = 0;
  21276. var subMesh;
  21277. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21278. for (; subIndex < subMeshes.length; subIndex++) {
  21279. subMesh = subMeshes.data[subIndex];
  21280. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21281. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21282. }
  21283. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21284. if (sortCompareFn) {
  21285. sortedArray.sort(sortCompareFn);
  21286. }
  21287. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21288. subMesh = sortedArray[subIndex];
  21289. if (transparent) {
  21290. var material = subMesh.getMaterial();
  21291. if (material && material.needDepthPrePass) {
  21292. var engine = material.getScene().getEngine();
  21293. engine.setColorWrite(false);
  21294. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21295. subMesh.render(false);
  21296. engine.setColorWrite(true);
  21297. }
  21298. }
  21299. subMesh.render(transparent);
  21300. }
  21301. };
  21302. /**
  21303. * Renders the submeshes in the order they were dispatched (no sort applied).
  21304. * @param subMeshes The submeshes to render
  21305. */
  21306. RenderingGroup.renderUnsorted = function (subMeshes) {
  21307. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21308. var submesh = subMeshes.data[subIndex];
  21309. submesh.render(false);
  21310. }
  21311. };
  21312. /**
  21313. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21314. * are rendered back to front if in the same alpha index.
  21315. *
  21316. * @param a The first submesh
  21317. * @param b The second submesh
  21318. * @returns The result of the comparison
  21319. */
  21320. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21321. // Alpha index first
  21322. if (a._alphaIndex > b._alphaIndex) {
  21323. return 1;
  21324. }
  21325. if (a._alphaIndex < b._alphaIndex) {
  21326. return -1;
  21327. }
  21328. // Then distance to camera
  21329. return RenderingGroup.backToFrontSortCompare(a, b);
  21330. };
  21331. /**
  21332. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21333. * are rendered back to front.
  21334. *
  21335. * @param a The first submesh
  21336. * @param b The second submesh
  21337. * @returns The result of the comparison
  21338. */
  21339. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21340. // Then distance to camera
  21341. if (a._distanceToCamera < b._distanceToCamera) {
  21342. return 1;
  21343. }
  21344. if (a._distanceToCamera > b._distanceToCamera) {
  21345. return -1;
  21346. }
  21347. return 0;
  21348. };
  21349. /**
  21350. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21351. * are rendered front to back (prevent overdraw).
  21352. *
  21353. * @param a The first submesh
  21354. * @param b The second submesh
  21355. * @returns The result of the comparison
  21356. */
  21357. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21358. // Then distance to camera
  21359. if (a._distanceToCamera < b._distanceToCamera) {
  21360. return -1;
  21361. }
  21362. if (a._distanceToCamera > b._distanceToCamera) {
  21363. return 1;
  21364. }
  21365. return 0;
  21366. };
  21367. /**
  21368. * Resets the different lists of submeshes to prepare a new frame.
  21369. */
  21370. RenderingGroup.prototype.prepare = function () {
  21371. this._opaqueSubMeshes.reset();
  21372. this._transparentSubMeshes.reset();
  21373. this._alphaTestSubMeshes.reset();
  21374. this._depthOnlySubMeshes.reset();
  21375. this._particleSystems.reset();
  21376. this._spriteManagers.reset();
  21377. this._edgesRenderers.reset();
  21378. };
  21379. RenderingGroup.prototype.dispose = function () {
  21380. this._opaqueSubMeshes.dispose();
  21381. this._transparentSubMeshes.dispose();
  21382. this._alphaTestSubMeshes.dispose();
  21383. this._depthOnlySubMeshes.dispose();
  21384. this._particleSystems.dispose();
  21385. this._spriteManagers.dispose();
  21386. this._edgesRenderers.dispose();
  21387. };
  21388. /**
  21389. * Inserts the submesh in its correct queue depending on its material.
  21390. * @param subMesh The submesh to dispatch
  21391. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21392. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21393. */
  21394. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21395. // Get mesh and materials if not provided
  21396. if (mesh === undefined) {
  21397. mesh = subMesh.getMesh();
  21398. }
  21399. if (material === undefined) {
  21400. material = subMesh.getMaterial();
  21401. }
  21402. if (material === null || material === undefined) {
  21403. return;
  21404. }
  21405. if (material.needAlphaBlendingForMesh(mesh)) {
  21406. this._transparentSubMeshes.push(subMesh);
  21407. }
  21408. else if (material.needAlphaTesting()) {
  21409. if (material.needDepthPrePass) {
  21410. this._depthOnlySubMeshes.push(subMesh);
  21411. }
  21412. this._alphaTestSubMeshes.push(subMesh);
  21413. }
  21414. else {
  21415. if (material.needDepthPrePass) {
  21416. this._depthOnlySubMeshes.push(subMesh);
  21417. }
  21418. this._opaqueSubMeshes.push(subMesh); // Opaque
  21419. }
  21420. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21421. this._edgesRenderers.push(mesh._edgesRenderer);
  21422. }
  21423. };
  21424. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21425. this._spriteManagers.push(spriteManager);
  21426. };
  21427. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21428. this._particleSystems.push(particleSystem);
  21429. };
  21430. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21431. if (this._particleSystems.length === 0) {
  21432. return;
  21433. }
  21434. // Particles
  21435. var activeCamera = this._scene.activeCamera;
  21436. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21437. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21438. var particleSystem = this._particleSystems.data[particleIndex];
  21439. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21440. continue;
  21441. }
  21442. var emitter = particleSystem.emitter;
  21443. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21444. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21445. }
  21446. }
  21447. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21448. };
  21449. RenderingGroup.prototype._renderSprites = function () {
  21450. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21451. return;
  21452. }
  21453. // Sprites
  21454. var activeCamera = this._scene.activeCamera;
  21455. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21456. for (var id = 0; id < this._spriteManagers.length; id++) {
  21457. var spriteManager = this._spriteManagers.data[id];
  21458. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21459. spriteManager.render();
  21460. }
  21461. }
  21462. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21463. };
  21464. return RenderingGroup;
  21465. }());
  21466. BABYLON.RenderingGroup = RenderingGroup;
  21467. })(BABYLON || (BABYLON = {}));
  21468. //# sourceMappingURL=babylon.renderingGroup.js.map
  21469. "use strict";
  21470. var BABYLON;
  21471. (function (BABYLON) {
  21472. var ClickInfo = /** @class */ (function () {
  21473. function ClickInfo() {
  21474. this._singleClick = false;
  21475. this._doubleClick = false;
  21476. this._hasSwiped = false;
  21477. this._ignore = false;
  21478. }
  21479. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21480. get: function () {
  21481. return this._singleClick;
  21482. },
  21483. set: function (b) {
  21484. this._singleClick = b;
  21485. },
  21486. enumerable: true,
  21487. configurable: true
  21488. });
  21489. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21490. get: function () {
  21491. return this._doubleClick;
  21492. },
  21493. set: function (b) {
  21494. this._doubleClick = b;
  21495. },
  21496. enumerable: true,
  21497. configurable: true
  21498. });
  21499. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21500. get: function () {
  21501. return this._hasSwiped;
  21502. },
  21503. set: function (b) {
  21504. this._hasSwiped = b;
  21505. },
  21506. enumerable: true,
  21507. configurable: true
  21508. });
  21509. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21510. get: function () {
  21511. return this._ignore;
  21512. },
  21513. set: function (b) {
  21514. this._ignore = b;
  21515. },
  21516. enumerable: true,
  21517. configurable: true
  21518. });
  21519. return ClickInfo;
  21520. }());
  21521. /**
  21522. * This class is used by the onRenderingGroupObservable
  21523. */
  21524. var RenderingGroupInfo = /** @class */ (function () {
  21525. function RenderingGroupInfo() {
  21526. }
  21527. /**
  21528. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21529. * This stage will be fired no matter what
  21530. */
  21531. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21532. /**
  21533. * Called before opaque object are rendered.
  21534. * This stage will be fired only if there's 3D Opaque content to render
  21535. */
  21536. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21537. /**
  21538. * Called after the opaque objects are rendered and before the transparent ones
  21539. * This stage will be fired only if there's 3D transparent content to render
  21540. */
  21541. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21542. /**
  21543. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21544. * This stage will be fired no matter what
  21545. */
  21546. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21547. return RenderingGroupInfo;
  21548. }());
  21549. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21550. /**
  21551. * Represents a scene to be rendered by the engine.
  21552. * @see http://doc.babylonjs.com/page.php?p=21911
  21553. */
  21554. var Scene = /** @class */ (function () {
  21555. /**
  21556. * @constructor
  21557. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21558. */
  21559. function Scene(engine) {
  21560. // Members
  21561. this.autoClear = true;
  21562. this.autoClearDepthAndStencil = true;
  21563. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21564. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21565. this._forceWireframe = false;
  21566. this._forcePointsCloud = false;
  21567. this.forceShowBoundingBoxes = false;
  21568. this.animationsEnabled = true;
  21569. this.useConstantAnimationDeltaTime = false;
  21570. this.constantlyUpdateMeshUnderPointer = false;
  21571. this.hoverCursor = "pointer";
  21572. this.defaultCursor = "";
  21573. /**
  21574. * This is used to call preventDefault() on pointer down
  21575. * in order to block unwanted artifacts like system double clicks
  21576. */
  21577. this.preventDefaultOnPointerDown = true;
  21578. // Metadata
  21579. this.metadata = null;
  21580. /**
  21581. * Use this array to add regular expressions used to disable offline support for specific urls
  21582. */
  21583. this.disableOfflineSupportExceptionRules = new Array();
  21584. /**
  21585. * An event triggered when the scene is disposed.
  21586. * @type {BABYLON.Observable}
  21587. */
  21588. this.onDisposeObservable = new BABYLON.Observable();
  21589. this._onDisposeObserver = null;
  21590. /**
  21591. * An event triggered before rendering the scene (right after animations and physics)
  21592. * @type {BABYLON.Observable}
  21593. */
  21594. this.onBeforeRenderObservable = new BABYLON.Observable();
  21595. this._onBeforeRenderObserver = null;
  21596. /**
  21597. * An event triggered after rendering the scene
  21598. * @type {BABYLON.Observable}
  21599. */
  21600. this.onAfterRenderObservable = new BABYLON.Observable();
  21601. this._onAfterRenderObserver = null;
  21602. /**
  21603. * An event triggered before animating the scene
  21604. * @type {BABYLON.Observable}
  21605. */
  21606. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21607. /**
  21608. * An event triggered after animations processing
  21609. * @type {BABYLON.Observable}
  21610. */
  21611. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21612. /**
  21613. * An event triggered before draw calls are ready to be sent
  21614. * @type {BABYLON.Observable}
  21615. */
  21616. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21617. /**
  21618. * An event triggered after draw calls have been sent
  21619. * @type {BABYLON.Observable}
  21620. */
  21621. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21622. /**
  21623. * An event triggered when physic simulation is about to be run
  21624. * @type {BABYLON.Observable}
  21625. */
  21626. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21627. /**
  21628. * An event triggered when physic simulation has been done
  21629. * @type {BABYLON.Observable}
  21630. */
  21631. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21632. /**
  21633. * An event triggered when the scene is ready
  21634. * @type {BABYLON.Observable}
  21635. */
  21636. this.onReadyObservable = new BABYLON.Observable();
  21637. /**
  21638. * An event triggered before rendering a camera
  21639. * @type {BABYLON.Observable}
  21640. */
  21641. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21642. this._onBeforeCameraRenderObserver = null;
  21643. /**
  21644. * An event triggered after rendering a camera
  21645. * @type {BABYLON.Observable}
  21646. */
  21647. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21648. this._onAfterCameraRenderObserver = null;
  21649. /**
  21650. * An event triggered when active meshes evaluation is about to start
  21651. * @type {BABYLON.Observable}
  21652. */
  21653. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21654. /**
  21655. * An event triggered when active meshes evaluation is done
  21656. * @type {BABYLON.Observable}
  21657. */
  21658. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21659. /**
  21660. * An event triggered when particles rendering is about to start
  21661. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21662. * @type {BABYLON.Observable}
  21663. */
  21664. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21665. /**
  21666. * An event triggered when particles rendering is done
  21667. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21668. * @type {BABYLON.Observable}
  21669. */
  21670. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21671. /**
  21672. * An event triggered when sprites rendering is about to start
  21673. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21674. * @type {BABYLON.Observable}
  21675. */
  21676. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21677. /**
  21678. * An event triggered when sprites rendering is done
  21679. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21680. * @type {BABYLON.Observable}
  21681. */
  21682. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21683. /**
  21684. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21685. * @type {BABYLON.Observable}
  21686. */
  21687. this.onDataLoadedObservable = new BABYLON.Observable();
  21688. /**
  21689. * An event triggered when a camera is created
  21690. * @type {BABYLON.Observable}
  21691. */
  21692. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21693. /**
  21694. * An event triggered when a camera is removed
  21695. * @type {BABYLON.Observable}
  21696. */
  21697. this.onCameraRemovedObservable = new BABYLON.Observable();
  21698. /**
  21699. * An event triggered when a light is created
  21700. * @type {BABYLON.Observable}
  21701. */
  21702. this.onNewLightAddedObservable = new BABYLON.Observable();
  21703. /**
  21704. * An event triggered when a light is removed
  21705. * @type {BABYLON.Observable}
  21706. */
  21707. this.onLightRemovedObservable = new BABYLON.Observable();
  21708. /**
  21709. * An event triggered when a geometry is created
  21710. * @type {BABYLON.Observable}
  21711. */
  21712. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21713. /**
  21714. * An event triggered when a geometry is removed
  21715. * @type {BABYLON.Observable}
  21716. */
  21717. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21718. /**
  21719. * An event triggered when a transform node is created
  21720. * @type {BABYLON.Observable}
  21721. */
  21722. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21723. /**
  21724. * An event triggered when a transform node is removed
  21725. * @type {BABYLON.Observable}
  21726. */
  21727. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21728. /**
  21729. * An event triggered when a mesh is created
  21730. * @type {BABYLON.Observable}
  21731. */
  21732. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21733. /**
  21734. * An event triggered when a mesh is removed
  21735. * @type {BABYLON.Observable}
  21736. */
  21737. this.onMeshRemovedObservable = new BABYLON.Observable();
  21738. /**
  21739. * An event triggered when render targets are about to be rendered
  21740. * Can happen multiple times per frame.
  21741. * @type {BABYLON.Observable}
  21742. */
  21743. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21744. /**
  21745. * An event triggered when render targets were rendered.
  21746. * Can happen multiple times per frame.
  21747. * @type {BABYLON.Observable}
  21748. */
  21749. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21750. /**
  21751. * An event triggered before calculating deterministic simulation step
  21752. * @type {BABYLON.Observable}
  21753. */
  21754. this.onBeforeStepObservable = new BABYLON.Observable();
  21755. /**
  21756. * An event triggered after calculating deterministic simulation step
  21757. * @type {BABYLON.Observable}
  21758. */
  21759. this.onAfterStepObservable = new BABYLON.Observable();
  21760. /**
  21761. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21762. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21763. * 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)
  21764. */
  21765. this.onRenderingGroupObservable = new BABYLON.Observable();
  21766. // Animations
  21767. this.animations = [];
  21768. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21769. /**
  21770. * 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).
  21771. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21772. */
  21773. this.onPrePointerObservable = new BABYLON.Observable();
  21774. /**
  21775. * Observable event triggered each time an input event is received from the rendering canvas
  21776. */
  21777. this.onPointerObservable = new BABYLON.Observable();
  21778. this._meshPickProceed = false;
  21779. this._currentPickResult = null;
  21780. this._previousPickResult = null;
  21781. this._totalPointersPressed = 0;
  21782. this._doubleClickOccured = false;
  21783. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21784. this.cameraToUseForPointers = null;
  21785. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21786. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21787. this._startingPointerTime = 0;
  21788. this._previousStartingPointerTime = 0;
  21789. // Deterministic lockstep
  21790. this._timeAccumulator = 0;
  21791. this._currentStepId = 0;
  21792. this._currentInternalStep = 0;
  21793. // Keyboard
  21794. /**
  21795. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21796. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21797. */
  21798. this.onPreKeyboardObservable = new BABYLON.Observable();
  21799. /**
  21800. * Observable event triggered each time an keyboard event is received from the hosting window
  21801. */
  21802. this.onKeyboardObservable = new BABYLON.Observable();
  21803. // Coordinate system
  21804. /**
  21805. * use right-handed coordinate system on this scene.
  21806. * @type {boolean}
  21807. */
  21808. this._useRightHandedSystem = false;
  21809. // Fog
  21810. this._fogEnabled = true;
  21811. this._fogMode = Scene.FOGMODE_NONE;
  21812. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21813. this.fogDensity = 0.1;
  21814. this.fogStart = 0;
  21815. this.fogEnd = 1000.0;
  21816. // Lights
  21817. /**
  21818. * is shadow enabled on this scene.
  21819. * @type {boolean}
  21820. */
  21821. this._shadowsEnabled = true;
  21822. /**
  21823. * is light enabled on this scene.
  21824. * @type {boolean}
  21825. */
  21826. this._lightsEnabled = true;
  21827. /**
  21828. * All of the lights added to this scene.
  21829. * @see BABYLON.Light
  21830. * @type {BABYLON.Light[]}
  21831. */
  21832. this.lights = new Array();
  21833. // Cameras
  21834. /** All of the cameras added to this scene. */
  21835. this.cameras = new Array();
  21836. /** All of the active cameras added to this scene. */
  21837. this.activeCameras = new Array();
  21838. // Meshes
  21839. /**
  21840. * All of the tranform nodes added to this scene.
  21841. * @see BABYLON.TransformNode
  21842. * @type {BABYLON.TransformNode[]}
  21843. */
  21844. this.transformNodes = new Array();
  21845. /**
  21846. * All of the (abstract) meshes added to this scene.
  21847. * @see BABYLON.AbstractMesh
  21848. * @type {BABYLON.AbstractMesh[]}
  21849. */
  21850. this.meshes = new Array();
  21851. /**
  21852. * All of the animation groups added to this scene.
  21853. * @see BABYLON.AnimationGroup
  21854. * @type {BABYLON.AnimationGroup[]}
  21855. */
  21856. this.animationGroups = new Array();
  21857. // Geometries
  21858. this._geometries = new Array();
  21859. this.materials = new Array();
  21860. this.multiMaterials = new Array();
  21861. // Textures
  21862. this._texturesEnabled = true;
  21863. this.textures = new Array();
  21864. // Particles
  21865. this.particlesEnabled = true;
  21866. this.particleSystems = new Array();
  21867. // Sprites
  21868. this.spritesEnabled = true;
  21869. this.spriteManagers = new Array();
  21870. /**
  21871. * The list of layers (background and foreground) of the scene.
  21872. */
  21873. this.layers = new Array();
  21874. /**
  21875. * The list of effect layers (highlights/glow) contained in the scene.
  21876. */
  21877. this.effectLayers = new Array();
  21878. // Skeletons
  21879. this._skeletonsEnabled = true;
  21880. this.skeletons = new Array();
  21881. // Morph targets
  21882. this.morphTargetManagers = new Array();
  21883. // Lens flares
  21884. this.lensFlaresEnabled = true;
  21885. this.lensFlareSystems = new Array();
  21886. // Collisions
  21887. this.collisionsEnabled = true;
  21888. /** Defines the gravity applied to this scene */
  21889. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21890. // Postprocesses
  21891. this.postProcesses = new Array();
  21892. this.postProcessesEnabled = true;
  21893. // Customs render targets
  21894. this.renderTargetsEnabled = true;
  21895. this.dumpNextRenderTargets = false;
  21896. this.customRenderTargets = new Array();
  21897. // Imported meshes
  21898. this.importedMeshesFiles = new Array();
  21899. // Probes
  21900. this.probesEnabled = true;
  21901. this.reflectionProbes = new Array();
  21902. this._actionManagers = new Array();
  21903. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21904. // Procedural textures
  21905. this.proceduralTexturesEnabled = true;
  21906. this._proceduralTextures = new Array();
  21907. this.soundTracks = new Array();
  21908. this._audioEnabled = true;
  21909. this._headphone = false;
  21910. // Performance counters
  21911. this._totalVertices = new BABYLON.PerfCounter();
  21912. this._activeIndices = new BABYLON.PerfCounter();
  21913. this._activeParticles = new BABYLON.PerfCounter();
  21914. this._activeBones = new BABYLON.PerfCounter();
  21915. this._animationTime = 0;
  21916. this.animationTimeScale = 1;
  21917. this._renderId = 0;
  21918. this._executeWhenReadyTimeoutId = -1;
  21919. this._intermediateRendering = false;
  21920. this._viewUpdateFlag = -1;
  21921. this._projectionUpdateFlag = -1;
  21922. this._alternateViewUpdateFlag = -1;
  21923. this._alternateProjectionUpdateFlag = -1;
  21924. this._toBeDisposed = new BABYLON.SmartArray(256);
  21925. this._activeRequests = new Array();
  21926. this._pendingData = new Array();
  21927. this._isDisposed = false;
  21928. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21929. this._activeMeshes = new BABYLON.SmartArray(256);
  21930. this._processedMaterials = new BABYLON.SmartArray(256);
  21931. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21932. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21933. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21934. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21935. this._activeAnimatables = new Array();
  21936. this._transformMatrix = BABYLON.Matrix.Zero();
  21937. this._useAlternateCameraConfiguration = false;
  21938. this._alternateRendering = false;
  21939. this.requireLightSorting = false;
  21940. this._depthRenderer = {};
  21941. this._activeMeshesFrozen = false;
  21942. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21943. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21944. this._engine.scenes.push(this);
  21945. this._uid = null;
  21946. this._renderingManager = new BABYLON.RenderingManager(this);
  21947. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21948. if (BABYLON.OutlineRenderer) {
  21949. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21950. }
  21951. if (BABYLON.Tools.IsWindowObjectExist()) {
  21952. this.attachControl();
  21953. }
  21954. //simplification queue
  21955. if (BABYLON.SimplificationQueue) {
  21956. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21957. }
  21958. //collision coordinator initialization. For now legacy per default.
  21959. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21960. // Uniform Buffer
  21961. this._createUbo();
  21962. // Default Image processing definition.
  21963. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21964. }
  21965. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21966. /** The fog is deactivated */
  21967. get: function () {
  21968. return Scene._FOGMODE_NONE;
  21969. },
  21970. enumerable: true,
  21971. configurable: true
  21972. });
  21973. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21974. /** The fog density is following an exponential function */
  21975. get: function () {
  21976. return Scene._FOGMODE_EXP;
  21977. },
  21978. enumerable: true,
  21979. configurable: true
  21980. });
  21981. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21982. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21983. get: function () {
  21984. return Scene._FOGMODE_EXP2;
  21985. },
  21986. enumerable: true,
  21987. configurable: true
  21988. });
  21989. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21990. /** The fog density is following a linear function. */
  21991. get: function () {
  21992. return Scene._FOGMODE_LINEAR;
  21993. },
  21994. enumerable: true,
  21995. configurable: true
  21996. });
  21997. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21998. /**
  21999. * Texture used in all pbr material as the reflection texture.
  22000. * As in the majority of the scene they are the same (exception for multi room and so on),
  22001. * this is easier to reference from here than from all the materials.
  22002. */
  22003. get: function () {
  22004. return this._environmentTexture;
  22005. },
  22006. /**
  22007. * Texture used in all pbr material as the reflection texture.
  22008. * As in the majority of the scene they are the same (exception for multi room and so on),
  22009. * this is easier to set here than in all the materials.
  22010. */
  22011. set: function (value) {
  22012. if (this._environmentTexture === value) {
  22013. return;
  22014. }
  22015. this._environmentTexture = value;
  22016. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22017. },
  22018. enumerable: true,
  22019. configurable: true
  22020. });
  22021. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22022. /**
  22023. * Default image processing configuration used either in the rendering
  22024. * Forward main pass or through the imageProcessingPostProcess if present.
  22025. * As in the majority of the scene they are the same (exception for multi camera),
  22026. * this is easier to reference from here than from all the materials and post process.
  22027. *
  22028. * No setter as we it is a shared configuration, you can set the values instead.
  22029. */
  22030. get: function () {
  22031. return this._imageProcessingConfiguration;
  22032. },
  22033. enumerable: true,
  22034. configurable: true
  22035. });
  22036. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22037. get: function () {
  22038. return this._forceWireframe;
  22039. },
  22040. set: function (value) {
  22041. if (this._forceWireframe === value) {
  22042. return;
  22043. }
  22044. this._forceWireframe = value;
  22045. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22046. },
  22047. enumerable: true,
  22048. configurable: true
  22049. });
  22050. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22051. get: function () {
  22052. return this._forcePointsCloud;
  22053. },
  22054. set: function (value) {
  22055. if (this._forcePointsCloud === value) {
  22056. return;
  22057. }
  22058. this._forcePointsCloud = value;
  22059. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22060. },
  22061. enumerable: true,
  22062. configurable: true
  22063. });
  22064. Object.defineProperty(Scene.prototype, "onDispose", {
  22065. /** A function to be executed when this scene is disposed. */
  22066. set: function (callback) {
  22067. if (this._onDisposeObserver) {
  22068. this.onDisposeObservable.remove(this._onDisposeObserver);
  22069. }
  22070. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Object.defineProperty(Scene.prototype, "beforeRender", {
  22076. /** A function to be executed before rendering this scene */
  22077. set: function (callback) {
  22078. if (this._onBeforeRenderObserver) {
  22079. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22080. }
  22081. if (callback) {
  22082. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22083. }
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Object.defineProperty(Scene.prototype, "afterRender", {
  22089. /** A function to be executed after rendering this scene */
  22090. set: function (callback) {
  22091. if (this._onAfterRenderObserver) {
  22092. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22093. }
  22094. if (callback) {
  22095. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22096. }
  22097. },
  22098. enumerable: true,
  22099. configurable: true
  22100. });
  22101. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22102. set: function (callback) {
  22103. if (this._onBeforeCameraRenderObserver) {
  22104. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22105. }
  22106. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22107. },
  22108. enumerable: true,
  22109. configurable: true
  22110. });
  22111. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22112. set: function (callback) {
  22113. if (this._onAfterCameraRenderObserver) {
  22114. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22115. }
  22116. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22117. },
  22118. enumerable: true,
  22119. configurable: true
  22120. });
  22121. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22122. get: function () {
  22123. if (!this._gamepadManager) {
  22124. this._gamepadManager = new BABYLON.GamepadManager(this);
  22125. }
  22126. return this._gamepadManager;
  22127. },
  22128. enumerable: true,
  22129. configurable: true
  22130. });
  22131. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22132. get: function () {
  22133. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22134. },
  22135. enumerable: true,
  22136. configurable: true
  22137. });
  22138. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22139. get: function () {
  22140. return this._useRightHandedSystem;
  22141. },
  22142. set: function (value) {
  22143. if (this._useRightHandedSystem === value) {
  22144. return;
  22145. }
  22146. this._useRightHandedSystem = value;
  22147. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22148. },
  22149. enumerable: true,
  22150. configurable: true
  22151. });
  22152. Scene.prototype.setStepId = function (newStepId) {
  22153. this._currentStepId = newStepId;
  22154. };
  22155. ;
  22156. Scene.prototype.getStepId = function () {
  22157. return this._currentStepId;
  22158. };
  22159. ;
  22160. Scene.prototype.getInternalStep = function () {
  22161. return this._currentInternalStep;
  22162. };
  22163. ;
  22164. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22165. get: function () {
  22166. return this._fogEnabled;
  22167. },
  22168. /**
  22169. * is fog enabled on this scene.
  22170. */
  22171. set: function (value) {
  22172. if (this._fogEnabled === value) {
  22173. return;
  22174. }
  22175. this._fogEnabled = value;
  22176. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22177. },
  22178. enumerable: true,
  22179. configurable: true
  22180. });
  22181. Object.defineProperty(Scene.prototype, "fogMode", {
  22182. get: function () {
  22183. return this._fogMode;
  22184. },
  22185. set: function (value) {
  22186. if (this._fogMode === value) {
  22187. return;
  22188. }
  22189. this._fogMode = value;
  22190. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22191. },
  22192. enumerable: true,
  22193. configurable: true
  22194. });
  22195. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22196. get: function () {
  22197. return this._shadowsEnabled;
  22198. },
  22199. set: function (value) {
  22200. if (this._shadowsEnabled === value) {
  22201. return;
  22202. }
  22203. this._shadowsEnabled = value;
  22204. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22205. },
  22206. enumerable: true,
  22207. configurable: true
  22208. });
  22209. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22210. get: function () {
  22211. return this._lightsEnabled;
  22212. },
  22213. set: function (value) {
  22214. if (this._lightsEnabled === value) {
  22215. return;
  22216. }
  22217. this._lightsEnabled = value;
  22218. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22219. },
  22220. enumerable: true,
  22221. configurable: true
  22222. });
  22223. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22224. /** The default material used on meshes when no material is affected */
  22225. get: function () {
  22226. if (!this._defaultMaterial) {
  22227. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22228. }
  22229. return this._defaultMaterial;
  22230. },
  22231. /** The default material used on meshes when no material is affected */
  22232. set: function (value) {
  22233. this._defaultMaterial = value;
  22234. },
  22235. enumerable: true,
  22236. configurable: true
  22237. });
  22238. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22239. get: function () {
  22240. return this._texturesEnabled;
  22241. },
  22242. set: function (value) {
  22243. if (this._texturesEnabled === value) {
  22244. return;
  22245. }
  22246. this._texturesEnabled = value;
  22247. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22248. },
  22249. enumerable: true,
  22250. configurable: true
  22251. });
  22252. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22253. get: function () {
  22254. return this._skeletonsEnabled;
  22255. },
  22256. set: function (value) {
  22257. if (this._skeletonsEnabled === value) {
  22258. return;
  22259. }
  22260. this._skeletonsEnabled = value;
  22261. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22262. },
  22263. enumerable: true,
  22264. configurable: true
  22265. });
  22266. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22267. get: function () {
  22268. if (!this._postProcessRenderPipelineManager) {
  22269. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22270. }
  22271. return this._postProcessRenderPipelineManager;
  22272. },
  22273. enumerable: true,
  22274. configurable: true
  22275. });
  22276. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22277. get: function () {
  22278. if (!this._mainSoundTrack) {
  22279. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22280. }
  22281. return this._mainSoundTrack;
  22282. },
  22283. enumerable: true,
  22284. configurable: true
  22285. });
  22286. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22287. get: function () {
  22288. return this._alternateRendering;
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22294. get: function () {
  22295. return this._frustumPlanes;
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22301. /**
  22302. * Gets the current geometry buffer associated to the scene.
  22303. */
  22304. get: function () {
  22305. return this._geometryBufferRenderer;
  22306. },
  22307. /**
  22308. * Sets the current geometry buffer for the scene.
  22309. */
  22310. set: function (geometryBufferRenderer) {
  22311. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22312. this._geometryBufferRenderer = geometryBufferRenderer;
  22313. }
  22314. },
  22315. enumerable: true,
  22316. configurable: true
  22317. });
  22318. Object.defineProperty(Scene.prototype, "debugLayer", {
  22319. // Properties
  22320. get: function () {
  22321. if (!this._debugLayer) {
  22322. this._debugLayer = new BABYLON.DebugLayer(this);
  22323. }
  22324. return this._debugLayer;
  22325. },
  22326. enumerable: true,
  22327. configurable: true
  22328. });
  22329. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22330. get: function () {
  22331. return this._workerCollisions;
  22332. },
  22333. set: function (enabled) {
  22334. if (!BABYLON.CollisionCoordinatorLegacy) {
  22335. return;
  22336. }
  22337. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22338. this._workerCollisions = enabled;
  22339. if (this.collisionCoordinator) {
  22340. this.collisionCoordinator.destroy();
  22341. }
  22342. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22343. this.collisionCoordinator.init(this);
  22344. },
  22345. enumerable: true,
  22346. configurable: true
  22347. });
  22348. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22349. get: function () {
  22350. return this._selectionOctree;
  22351. },
  22352. enumerable: true,
  22353. configurable: true
  22354. });
  22355. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22356. /**
  22357. * The mesh that is currently under the pointer.
  22358. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22359. */
  22360. get: function () {
  22361. return this._pointerOverMesh;
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. Object.defineProperty(Scene.prototype, "pointerX", {
  22367. /**
  22368. * Current on-screen X position of the pointer
  22369. * @return {number} X position of the pointer
  22370. */
  22371. get: function () {
  22372. return this._pointerX;
  22373. },
  22374. enumerable: true,
  22375. configurable: true
  22376. });
  22377. Object.defineProperty(Scene.prototype, "pointerY", {
  22378. /**
  22379. * Current on-screen Y position of the pointer
  22380. * @return {number} Y position of the pointer
  22381. */
  22382. get: function () {
  22383. return this._pointerY;
  22384. },
  22385. enumerable: true,
  22386. configurable: true
  22387. });
  22388. Scene.prototype.getCachedMaterial = function () {
  22389. return this._cachedMaterial;
  22390. };
  22391. Scene.prototype.getCachedEffect = function () {
  22392. return this._cachedEffect;
  22393. };
  22394. Scene.prototype.getCachedVisibility = function () {
  22395. return this._cachedVisibility;
  22396. };
  22397. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22398. if (visibility === void 0) { visibility = 1; }
  22399. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22400. };
  22401. Scene.prototype.getBoundingBoxRenderer = function () {
  22402. if (!this._boundingBoxRenderer) {
  22403. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22404. }
  22405. return this._boundingBoxRenderer;
  22406. };
  22407. Scene.prototype.getOutlineRenderer = function () {
  22408. return this._outlineRenderer;
  22409. };
  22410. Scene.prototype.getEngine = function () {
  22411. return this._engine;
  22412. };
  22413. Scene.prototype.getTotalVertices = function () {
  22414. return this._totalVertices.current;
  22415. };
  22416. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22417. get: function () {
  22418. return this._totalVertices;
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. Scene.prototype.getActiveIndices = function () {
  22424. return this._activeIndices.current;
  22425. };
  22426. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22427. get: function () {
  22428. return this._activeIndices;
  22429. },
  22430. enumerable: true,
  22431. configurable: true
  22432. });
  22433. Scene.prototype.getActiveParticles = function () {
  22434. return this._activeParticles.current;
  22435. };
  22436. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22437. get: function () {
  22438. return this._activeParticles;
  22439. },
  22440. enumerable: true,
  22441. configurable: true
  22442. });
  22443. Scene.prototype.getActiveBones = function () {
  22444. return this._activeBones.current;
  22445. };
  22446. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22447. get: function () {
  22448. return this._activeBones;
  22449. },
  22450. enumerable: true,
  22451. configurable: true
  22452. });
  22453. // Stats
  22454. Scene.prototype.getInterFramePerfCounter = function () {
  22455. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22456. return 0;
  22457. };
  22458. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22459. get: function () {
  22460. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22461. return null;
  22462. },
  22463. enumerable: true,
  22464. configurable: true
  22465. });
  22466. Scene.prototype.getLastFrameDuration = function () {
  22467. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22468. return 0;
  22469. };
  22470. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22471. get: function () {
  22472. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22473. return null;
  22474. },
  22475. enumerable: true,
  22476. configurable: true
  22477. });
  22478. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22479. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22480. return 0;
  22481. };
  22482. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22483. get: function () {
  22484. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22485. return null;
  22486. },
  22487. enumerable: true,
  22488. configurable: true
  22489. });
  22490. Scene.prototype.getActiveMeshes = function () {
  22491. return this._activeMeshes;
  22492. };
  22493. Scene.prototype.getRenderTargetsDuration = function () {
  22494. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22495. return 0;
  22496. };
  22497. Scene.prototype.getRenderDuration = function () {
  22498. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22499. return 0;
  22500. };
  22501. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22502. get: function () {
  22503. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22504. return null;
  22505. },
  22506. enumerable: true,
  22507. configurable: true
  22508. });
  22509. Scene.prototype.getParticlesDuration = function () {
  22510. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22511. return 0;
  22512. };
  22513. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22514. get: function () {
  22515. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22516. return null;
  22517. },
  22518. enumerable: true,
  22519. configurable: true
  22520. });
  22521. Scene.prototype.getSpritesDuration = function () {
  22522. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22523. return 0;
  22524. };
  22525. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22526. get: function () {
  22527. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22528. return null;
  22529. },
  22530. enumerable: true,
  22531. configurable: true
  22532. });
  22533. Scene.prototype.getAnimationRatio = function () {
  22534. return this._animationRatio;
  22535. };
  22536. Scene.prototype.getRenderId = function () {
  22537. return this._renderId;
  22538. };
  22539. Scene.prototype.incrementRenderId = function () {
  22540. this._renderId++;
  22541. };
  22542. Scene.prototype._updatePointerPosition = function (evt) {
  22543. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22544. if (!canvasRect) {
  22545. return;
  22546. }
  22547. this._pointerX = evt.clientX - canvasRect.left;
  22548. this._pointerY = evt.clientY - canvasRect.top;
  22549. this._unTranslatedPointerX = this._pointerX;
  22550. this._unTranslatedPointerY = this._pointerY;
  22551. };
  22552. Scene.prototype._createUbo = function () {
  22553. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22554. this._sceneUbo.addUniform("viewProjection", 16);
  22555. this._sceneUbo.addUniform("view", 16);
  22556. };
  22557. Scene.prototype._createAlternateUbo = function () {
  22558. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22559. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22560. this._alternateSceneUbo.addUniform("view", 16);
  22561. };
  22562. // Pointers handling
  22563. /**
  22564. * Use this method to simulate a pointer move on a mesh
  22565. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22566. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22567. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22568. */
  22569. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22570. var evt = new PointerEvent("pointermove", pointerEventInit);
  22571. return this._processPointerMove(pickResult, evt);
  22572. };
  22573. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22574. var canvas = this._engine.getRenderingCanvas();
  22575. if (!canvas) {
  22576. return this;
  22577. }
  22578. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22579. this.setPointerOverSprite(null);
  22580. this.setPointerOverMesh(pickResult.pickedMesh);
  22581. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22582. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22583. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22584. }
  22585. else {
  22586. canvas.style.cursor = this.hoverCursor;
  22587. }
  22588. }
  22589. else {
  22590. canvas.style.cursor = this.defaultCursor;
  22591. }
  22592. }
  22593. else {
  22594. this.setPointerOverMesh(null);
  22595. // Sprites
  22596. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22597. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22598. this.setPointerOverSprite(pickResult.pickedSprite);
  22599. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22600. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22601. }
  22602. else {
  22603. canvas.style.cursor = this.hoverCursor;
  22604. }
  22605. }
  22606. else {
  22607. this.setPointerOverSprite(null);
  22608. // Restore pointer
  22609. canvas.style.cursor = this.defaultCursor;
  22610. }
  22611. }
  22612. if (pickResult) {
  22613. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22614. if (this.onPointerMove) {
  22615. this.onPointerMove(evt, pickResult, type);
  22616. }
  22617. if (this.onPointerObservable.hasObservers()) {
  22618. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22619. this.onPointerObservable.notifyObservers(pi, type);
  22620. }
  22621. }
  22622. return this;
  22623. };
  22624. /**
  22625. * Use this method to simulate a pointer down on a mesh
  22626. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22627. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22628. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22629. */
  22630. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22631. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22632. return this._processPointerDown(pickResult, evt);
  22633. };
  22634. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22635. var _this = this;
  22636. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22637. this._pickedDownMesh = pickResult.pickedMesh;
  22638. var actionManager = pickResult.pickedMesh.actionManager;
  22639. if (actionManager) {
  22640. if (actionManager.hasPickTriggers) {
  22641. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22642. switch (evt.button) {
  22643. case 0:
  22644. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22645. break;
  22646. case 1:
  22647. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22648. break;
  22649. case 2:
  22650. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22651. break;
  22652. }
  22653. }
  22654. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22655. window.setTimeout(function () {
  22656. 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);
  22657. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22658. if (_this._totalPointersPressed !== 0 &&
  22659. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22660. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22661. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22662. _this._startingPointerTime = 0;
  22663. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22664. }
  22665. }
  22666. }, Scene.LongPressDelay);
  22667. }
  22668. }
  22669. }
  22670. if (pickResult) {
  22671. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22672. if (this.onPointerDown) {
  22673. this.onPointerDown(evt, pickResult, type);
  22674. }
  22675. if (this.onPointerObservable.hasObservers()) {
  22676. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22677. this.onPointerObservable.notifyObservers(pi, type);
  22678. }
  22679. }
  22680. return this;
  22681. };
  22682. /**
  22683. * Use this method to simulate a pointer up on a mesh
  22684. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22685. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22686. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22687. */
  22688. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22689. var evt = new PointerEvent("pointerup", pointerEventInit);
  22690. var clickInfo = new ClickInfo();
  22691. clickInfo.singleClick = true;
  22692. clickInfo.ignore = true;
  22693. return this._processPointerUp(pickResult, evt, clickInfo);
  22694. };
  22695. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22696. if (pickResult && pickResult && pickResult.pickedMesh) {
  22697. this._pickedUpMesh = pickResult.pickedMesh;
  22698. if (this._pickedDownMesh === this._pickedUpMesh) {
  22699. if (this.onPointerPick) {
  22700. this.onPointerPick(evt, pickResult);
  22701. }
  22702. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22703. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22704. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22705. this.onPointerObservable.notifyObservers(pi, type_1);
  22706. }
  22707. }
  22708. if (pickResult.pickedMesh.actionManager) {
  22709. if (clickInfo.ignore) {
  22710. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22711. }
  22712. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22713. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22714. }
  22715. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22716. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22717. }
  22718. }
  22719. }
  22720. if (this._pickedDownMesh &&
  22721. this._pickedDownMesh.actionManager &&
  22722. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22723. this._pickedDownMesh !== this._pickedUpMesh) {
  22724. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22725. }
  22726. var type = BABYLON.PointerEventTypes.POINTERUP;
  22727. if (this.onPointerObservable.hasObservers()) {
  22728. if (!clickInfo.ignore) {
  22729. if (!clickInfo.hasSwiped) {
  22730. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22731. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22732. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22733. this.onPointerObservable.notifyObservers(pi, type_2);
  22734. }
  22735. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22736. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22737. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22738. this.onPointerObservable.notifyObservers(pi, type_3);
  22739. }
  22740. }
  22741. }
  22742. else {
  22743. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22744. this.onPointerObservable.notifyObservers(pi, type);
  22745. }
  22746. }
  22747. if (this.onPointerUp) {
  22748. this.onPointerUp(evt, pickResult, type);
  22749. }
  22750. return this;
  22751. };
  22752. /**
  22753. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22754. * @param attachUp defines if you want to attach events to pointerup
  22755. * @param attachDown defines if you want to attach events to pointerdown
  22756. * @param attachMove defines if you want to attach events to pointermove
  22757. */
  22758. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22759. var _this = this;
  22760. if (attachUp === void 0) { attachUp = true; }
  22761. if (attachDown === void 0) { attachDown = true; }
  22762. if (attachMove === void 0) { attachMove = true; }
  22763. this._initActionManager = function (act, clickInfo) {
  22764. if (!_this._meshPickProceed) {
  22765. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22766. _this._currentPickResult = pickResult;
  22767. if (pickResult) {
  22768. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22769. }
  22770. _this._meshPickProceed = true;
  22771. }
  22772. return act;
  22773. };
  22774. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22775. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22776. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22777. btn !== _this._previousButtonPressed) {
  22778. _this._doubleClickOccured = false;
  22779. clickInfo.singleClick = true;
  22780. clickInfo.ignore = false;
  22781. cb(clickInfo, _this._currentPickResult);
  22782. }
  22783. };
  22784. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22785. var clickInfo = new ClickInfo();
  22786. _this._currentPickResult = null;
  22787. var act = null;
  22788. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22789. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22790. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22791. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22792. act = _this._initActionManager(act, clickInfo);
  22793. if (act)
  22794. checkPicking = act.hasPickTriggers;
  22795. }
  22796. if (checkPicking) {
  22797. var btn = evt.button;
  22798. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22799. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22800. if (!clickInfo.hasSwiped) {
  22801. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22802. if (!checkSingleClickImmediately) {
  22803. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22804. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22805. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22806. act = _this._initActionManager(act, clickInfo);
  22807. if (act)
  22808. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22809. }
  22810. }
  22811. if (checkSingleClickImmediately) {
  22812. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22813. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22814. btn !== _this._previousButtonPressed) {
  22815. clickInfo.singleClick = true;
  22816. cb(clickInfo, _this._currentPickResult);
  22817. }
  22818. }
  22819. else {
  22820. // wait that no double click has been raised during the double click delay
  22821. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22822. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22823. }
  22824. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22825. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22826. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22827. act = _this._initActionManager(act, clickInfo);
  22828. if (act)
  22829. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22830. }
  22831. if (checkDoubleClick) {
  22832. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22833. if (btn === _this._previousButtonPressed &&
  22834. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22835. !_this._doubleClickOccured) {
  22836. // pointer has not moved for 2 clicks, it's a double click
  22837. if (!clickInfo.hasSwiped &&
  22838. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22839. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22840. _this._previousStartingPointerTime = 0;
  22841. _this._doubleClickOccured = true;
  22842. clickInfo.doubleClick = true;
  22843. clickInfo.ignore = false;
  22844. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22845. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22846. }
  22847. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22848. cb(clickInfo, _this._currentPickResult);
  22849. }
  22850. else {
  22851. _this._doubleClickOccured = false;
  22852. _this._previousStartingPointerTime = _this._startingPointerTime;
  22853. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22854. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22855. _this._previousButtonPressed = btn;
  22856. if (Scene.ExclusiveDoubleClickMode) {
  22857. if (_this._previousDelayedSimpleClickTimeout) {
  22858. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22859. }
  22860. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22861. cb(clickInfo, _this._previousPickResult);
  22862. }
  22863. else {
  22864. cb(clickInfo, _this._currentPickResult);
  22865. }
  22866. }
  22867. }
  22868. else {
  22869. _this._doubleClickOccured = false;
  22870. _this._previousStartingPointerTime = _this._startingPointerTime;
  22871. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22872. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22873. _this._previousButtonPressed = btn;
  22874. }
  22875. }
  22876. }
  22877. }
  22878. clickInfo.ignore = true;
  22879. cb(clickInfo, _this._currentPickResult);
  22880. };
  22881. this._spritePredicate = function (sprite) {
  22882. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22883. };
  22884. this._onPointerMove = function (evt) {
  22885. _this._updatePointerPosition(evt);
  22886. // PreObservable support
  22887. if (_this.onPrePointerObservable.hasObservers()) {
  22888. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22889. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22890. _this.onPrePointerObservable.notifyObservers(pi, type);
  22891. if (pi.skipOnPointerObservable) {
  22892. return;
  22893. }
  22894. }
  22895. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22896. return;
  22897. }
  22898. if (!_this.pointerMovePredicate) {
  22899. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22900. }
  22901. // Meshes
  22902. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22903. _this._processPointerMove(pickResult, evt);
  22904. };
  22905. this._onPointerDown = function (evt) {
  22906. _this._totalPointersPressed++;
  22907. _this._pickedDownMesh = null;
  22908. _this._meshPickProceed = false;
  22909. _this._updatePointerPosition(evt);
  22910. if (_this.preventDefaultOnPointerDown && canvas) {
  22911. evt.preventDefault();
  22912. canvas.focus();
  22913. }
  22914. // PreObservable support
  22915. if (_this.onPrePointerObservable.hasObservers()) {
  22916. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22917. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22918. _this.onPrePointerObservable.notifyObservers(pi, type);
  22919. if (pi.skipOnPointerObservable) {
  22920. return;
  22921. }
  22922. }
  22923. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22924. return;
  22925. }
  22926. _this._startingPointerPosition.x = _this._pointerX;
  22927. _this._startingPointerPosition.y = _this._pointerY;
  22928. _this._startingPointerTime = new Date().getTime();
  22929. if (!_this.pointerDownPredicate) {
  22930. _this.pointerDownPredicate = function (mesh) {
  22931. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22932. };
  22933. }
  22934. // Meshes
  22935. _this._pickedDownMesh = null;
  22936. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22937. _this._processPointerDown(pickResult, evt);
  22938. // Sprites
  22939. _this._pickedDownSprite = null;
  22940. if (_this.spriteManagers.length > 0) {
  22941. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22942. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22943. if (pickResult.pickedSprite.actionManager) {
  22944. _this._pickedDownSprite = pickResult.pickedSprite;
  22945. switch (evt.button) {
  22946. case 0:
  22947. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22948. break;
  22949. case 1:
  22950. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22951. break;
  22952. case 2:
  22953. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22954. break;
  22955. }
  22956. if (pickResult.pickedSprite.actionManager) {
  22957. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22958. }
  22959. }
  22960. }
  22961. }
  22962. };
  22963. this._onPointerUp = function (evt) {
  22964. if (_this._totalPointersPressed === 0) {
  22965. return; // So we need to test it the pointer down was pressed before.
  22966. }
  22967. _this._totalPointersPressed--;
  22968. _this._pickedUpMesh = null;
  22969. _this._meshPickProceed = false;
  22970. _this._updatePointerPosition(evt);
  22971. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22972. // PreObservable support
  22973. if (_this.onPrePointerObservable.hasObservers()) {
  22974. if (!clickInfo.ignore) {
  22975. if (!clickInfo.hasSwiped) {
  22976. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22977. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22978. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22979. _this.onPrePointerObservable.notifyObservers(pi, type);
  22980. if (pi.skipOnPointerObservable) {
  22981. return;
  22982. }
  22983. }
  22984. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22985. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22986. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22987. _this.onPrePointerObservable.notifyObservers(pi, type);
  22988. if (pi.skipOnPointerObservable) {
  22989. return;
  22990. }
  22991. }
  22992. }
  22993. }
  22994. else {
  22995. var type = BABYLON.PointerEventTypes.POINTERUP;
  22996. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22997. _this.onPrePointerObservable.notifyObservers(pi, type);
  22998. if (pi.skipOnPointerObservable) {
  22999. return;
  23000. }
  23001. }
  23002. }
  23003. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23004. return;
  23005. }
  23006. if (!_this.pointerUpPredicate) {
  23007. _this.pointerUpPredicate = function (mesh) {
  23008. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23009. };
  23010. }
  23011. // Meshes
  23012. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23013. _this._initActionManager(null, clickInfo);
  23014. }
  23015. if (!pickResult) {
  23016. pickResult = _this._currentPickResult;
  23017. }
  23018. _this._processPointerUp(pickResult, evt, clickInfo);
  23019. // Sprites
  23020. if (_this.spriteManagers.length > 0) {
  23021. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23022. if (spritePickResult) {
  23023. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23024. if (spritePickResult.pickedSprite.actionManager) {
  23025. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23026. if (spritePickResult.pickedSprite.actionManager) {
  23027. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23028. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23029. }
  23030. }
  23031. }
  23032. }
  23033. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23034. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23035. }
  23036. }
  23037. }
  23038. _this._previousPickResult = _this._currentPickResult;
  23039. });
  23040. };
  23041. this._onKeyDown = function (evt) {
  23042. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23043. if (_this.onPreKeyboardObservable.hasObservers()) {
  23044. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23045. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23046. if (pi.skipOnPointerObservable) {
  23047. return;
  23048. }
  23049. }
  23050. if (_this.onKeyboardObservable.hasObservers()) {
  23051. var pi = new BABYLON.KeyboardInfo(type, evt);
  23052. _this.onKeyboardObservable.notifyObservers(pi, type);
  23053. }
  23054. if (_this.actionManager) {
  23055. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23056. }
  23057. };
  23058. this._onKeyUp = function (evt) {
  23059. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23060. if (_this.onPreKeyboardObservable.hasObservers()) {
  23061. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23062. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23063. if (pi.skipOnPointerObservable) {
  23064. return;
  23065. }
  23066. }
  23067. if (_this.onKeyboardObservable.hasObservers()) {
  23068. var pi = new BABYLON.KeyboardInfo(type, evt);
  23069. _this.onKeyboardObservable.notifyObservers(pi, type);
  23070. }
  23071. if (_this.actionManager) {
  23072. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23073. }
  23074. };
  23075. var engine = this.getEngine();
  23076. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23077. if (!canvas) {
  23078. return;
  23079. }
  23080. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23081. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23082. });
  23083. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23084. if (!canvas) {
  23085. return;
  23086. }
  23087. canvas.removeEventListener("keydown", _this._onKeyDown);
  23088. canvas.removeEventListener("keyup", _this._onKeyUp);
  23089. });
  23090. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23091. var canvas = this._engine.getRenderingCanvas();
  23092. if (!canvas) {
  23093. return;
  23094. }
  23095. if (attachMove) {
  23096. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23097. // Wheel
  23098. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23099. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23100. }
  23101. if (attachDown) {
  23102. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23103. }
  23104. if (attachUp) {
  23105. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23106. }
  23107. canvas.tabIndex = 1;
  23108. };
  23109. Scene.prototype.detachControl = function () {
  23110. var engine = this.getEngine();
  23111. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23112. var canvas = engine.getRenderingCanvas();
  23113. if (!canvas) {
  23114. return;
  23115. }
  23116. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23117. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23118. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23119. if (this._onCanvasBlurObserver) {
  23120. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23121. }
  23122. if (this._onCanvasFocusObserver) {
  23123. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23124. }
  23125. // Wheel
  23126. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23127. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23128. // Keyboard
  23129. canvas.removeEventListener("keydown", this._onKeyDown);
  23130. canvas.removeEventListener("keyup", this._onKeyUp);
  23131. // Observables
  23132. this.onKeyboardObservable.clear();
  23133. this.onPreKeyboardObservable.clear();
  23134. this.onPointerObservable.clear();
  23135. this.onPrePointerObservable.clear();
  23136. };
  23137. /**
  23138. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23139. * Delay loaded resources are not taking in account
  23140. * @return true if all required resources are ready
  23141. */
  23142. Scene.prototype.isReady = function () {
  23143. if (this._isDisposed) {
  23144. return false;
  23145. }
  23146. if (this._pendingData.length > 0) {
  23147. return false;
  23148. }
  23149. var index;
  23150. var engine = this.getEngine();
  23151. // Geometries
  23152. for (index = 0; index < this._geometries.length; index++) {
  23153. var geometry = this._geometries[index];
  23154. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23155. return false;
  23156. }
  23157. }
  23158. // Meshes
  23159. for (index = 0; index < this.meshes.length; index++) {
  23160. var mesh = this.meshes[index];
  23161. if (!mesh.isEnabled()) {
  23162. continue;
  23163. }
  23164. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23165. continue;
  23166. }
  23167. if (!mesh.isReady(true)) {
  23168. return false;
  23169. }
  23170. // Effect layers
  23171. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23172. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23173. var layer = _a[_i];
  23174. if (!layer.hasMesh(mesh)) {
  23175. continue;
  23176. }
  23177. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23178. var subMesh = _c[_b];
  23179. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23180. return false;
  23181. }
  23182. }
  23183. }
  23184. }
  23185. // Particles
  23186. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23187. var particleSystem = _e[_d];
  23188. if (!particleSystem.isReady()) {
  23189. return false;
  23190. }
  23191. }
  23192. return true;
  23193. };
  23194. Scene.prototype.resetCachedMaterial = function () {
  23195. this._cachedMaterial = null;
  23196. this._cachedEffect = null;
  23197. this._cachedVisibility = null;
  23198. };
  23199. Scene.prototype.registerBeforeRender = function (func) {
  23200. this.onBeforeRenderObservable.add(func);
  23201. };
  23202. Scene.prototype.unregisterBeforeRender = function (func) {
  23203. this.onBeforeRenderObservable.removeCallback(func);
  23204. };
  23205. Scene.prototype.registerAfterRender = function (func) {
  23206. this.onAfterRenderObservable.add(func);
  23207. };
  23208. Scene.prototype.unregisterAfterRender = function (func) {
  23209. this.onAfterRenderObservable.removeCallback(func);
  23210. };
  23211. Scene.prototype._executeOnceBeforeRender = function (func) {
  23212. var _this = this;
  23213. var execFunc = function () {
  23214. func();
  23215. setTimeout(function () {
  23216. _this.unregisterBeforeRender(execFunc);
  23217. });
  23218. };
  23219. this.registerBeforeRender(execFunc);
  23220. };
  23221. /**
  23222. * The provided function will run before render once and will be disposed afterwards.
  23223. * A timeout delay can be provided so that the function will be executed in N ms.
  23224. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23225. * @param func The function to be executed.
  23226. * @param timeout optional delay in ms
  23227. */
  23228. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23229. var _this = this;
  23230. if (timeout !== undefined) {
  23231. setTimeout(function () {
  23232. _this._executeOnceBeforeRender(func);
  23233. }, timeout);
  23234. }
  23235. else {
  23236. this._executeOnceBeforeRender(func);
  23237. }
  23238. };
  23239. Scene.prototype._addPendingData = function (data) {
  23240. this._pendingData.push(data);
  23241. };
  23242. Scene.prototype._removePendingData = function (data) {
  23243. var wasLoading = this.isLoading;
  23244. var index = this._pendingData.indexOf(data);
  23245. if (index !== -1) {
  23246. this._pendingData.splice(index, 1);
  23247. }
  23248. if (wasLoading && !this.isLoading) {
  23249. this.onDataLoadedObservable.notifyObservers(this);
  23250. }
  23251. };
  23252. Scene.prototype.getWaitingItemsCount = function () {
  23253. return this._pendingData.length;
  23254. };
  23255. Object.defineProperty(Scene.prototype, "isLoading", {
  23256. get: function () {
  23257. return this._pendingData.length > 0;
  23258. },
  23259. enumerable: true,
  23260. configurable: true
  23261. });
  23262. /**
  23263. * Registers a function to be executed when the scene is ready.
  23264. * @param {Function} func - the function to be executed.
  23265. */
  23266. Scene.prototype.executeWhenReady = function (func) {
  23267. var _this = this;
  23268. this.onReadyObservable.add(func);
  23269. if (this._executeWhenReadyTimeoutId !== -1) {
  23270. return;
  23271. }
  23272. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23273. _this._checkIsReady();
  23274. }, 150);
  23275. };
  23276. /**
  23277. * Returns a promise that resolves when the scene is ready.
  23278. * @returns A promise that resolves when the scene is ready.
  23279. */
  23280. Scene.prototype.whenReadyAsync = function () {
  23281. var _this = this;
  23282. return new Promise(function (resolve) {
  23283. _this.executeWhenReady(function () {
  23284. resolve();
  23285. });
  23286. });
  23287. };
  23288. Scene.prototype._checkIsReady = function () {
  23289. var _this = this;
  23290. if (this.isReady()) {
  23291. this.onReadyObservable.notifyObservers(this);
  23292. this.onReadyObservable.clear();
  23293. this._executeWhenReadyTimeoutId = -1;
  23294. return;
  23295. }
  23296. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23297. _this._checkIsReady();
  23298. }, 150);
  23299. };
  23300. // Animations
  23301. /**
  23302. * Will start the animation sequence of a given target
  23303. * @param target defines the target
  23304. * @param from defines from which frame should animation start
  23305. * @param to defines until which frame should animation run.
  23306. * @param weight defines the weight to apply to the animation (1.0 by default)
  23307. * @param loop defines if the animation loops
  23308. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23309. * @param onAnimationEnd defines the function to be executed when the animation ends
  23310. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23311. * @returns the animatable object created for this animation
  23312. * @see BABYLON.Animatable
  23313. */
  23314. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23315. if (weight === void 0) { weight = 1.0; }
  23316. if (speedRatio === void 0) { speedRatio = 1.0; }
  23317. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23318. returnedAnimatable.weight = weight;
  23319. return returnedAnimatable;
  23320. };
  23321. /**
  23322. * Will start the animation sequence of a given target
  23323. * @param target defines the target
  23324. * @param from defines from which frame should animation start
  23325. * @param to defines until which frame should animation run.
  23326. * @param loop defines if the animation loops
  23327. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23328. * @param onAnimationEnd defines the function to be executed when the animation ends
  23329. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23330. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23331. * @returns the animatable object created for this animation
  23332. * @see BABYLON.Animatable
  23333. */
  23334. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23335. if (speedRatio === void 0) { speedRatio = 1.0; }
  23336. if (stopCurrent === void 0) { stopCurrent = true; }
  23337. if (from > to && speedRatio > 0) {
  23338. speedRatio *= -1;
  23339. }
  23340. if (stopCurrent) {
  23341. this.stopAnimation(target);
  23342. }
  23343. if (!animatable) {
  23344. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23345. }
  23346. // Local animations
  23347. if (target.animations) {
  23348. animatable.appendAnimations(target, target.animations);
  23349. }
  23350. // Children animations
  23351. if (target.getAnimatables) {
  23352. var animatables = target.getAnimatables();
  23353. for (var index = 0; index < animatables.length; index++) {
  23354. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23355. }
  23356. }
  23357. animatable.reset();
  23358. return animatable;
  23359. };
  23360. /**
  23361. * Begin a new animation on a given node
  23362. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23363. * @param {BABYLON.Animation[]} defines the list of animations to start
  23364. * @param {number} from defines the initial value
  23365. * @param {number} to defines the final value
  23366. * @param {boolean} loop defines if you want animation to loop (off by default)
  23367. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23368. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23369. * @returns the list of created animatables
  23370. */
  23371. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23372. if (speedRatio === undefined) {
  23373. speedRatio = 1.0;
  23374. }
  23375. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23376. return animatable;
  23377. };
  23378. /**
  23379. * Begin a new animation on a given node and its hierarchy
  23380. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23381. * @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.
  23382. * @param {BABYLON.Animation[]} defines the list of animations to start
  23383. * @param {number} from defines the initial value
  23384. * @param {number} to defines the final value
  23385. * @param {boolean} loop defines if you want animation to loop (off by default)
  23386. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23387. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23388. * @returns the list of animatables created for all nodes
  23389. */
  23390. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23391. var children = target.getDescendants(directDescendantsOnly);
  23392. var result = [];
  23393. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23394. var child = children_1[_i];
  23395. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23396. }
  23397. return result;
  23398. };
  23399. Scene.prototype.getAnimatableByTarget = function (target) {
  23400. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23401. if (this._activeAnimatables[index].target === target) {
  23402. return this._activeAnimatables[index];
  23403. }
  23404. }
  23405. return null;
  23406. };
  23407. /**
  23408. * Gets all animatables associated with a given target
  23409. * @param target defines the target to look animatables for
  23410. * @returns an array of Animatables
  23411. */
  23412. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23413. var result = [];
  23414. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23415. if (this._activeAnimatables[index].target === target) {
  23416. result.push(this._activeAnimatables[index]);
  23417. }
  23418. }
  23419. return result;
  23420. };
  23421. Object.defineProperty(Scene.prototype, "animatables", {
  23422. get: function () {
  23423. return this._activeAnimatables;
  23424. },
  23425. enumerable: true,
  23426. configurable: true
  23427. });
  23428. /**
  23429. * Will stop the animation of the given target
  23430. * @param target - the target
  23431. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23432. * @see beginAnimation
  23433. */
  23434. Scene.prototype.stopAnimation = function (target, animationName) {
  23435. var animatables = this.getAllAnimatablesByTarget(target);
  23436. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23437. var animatable = animatables_1[_i];
  23438. animatable.stop(animationName);
  23439. }
  23440. };
  23441. /**
  23442. * Stops and removes all animations that have been applied to the scene
  23443. */
  23444. Scene.prototype.stopAllAnimations = function () {
  23445. if (this._activeAnimatables) {
  23446. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23447. this._activeAnimatables[i].stop();
  23448. }
  23449. this._activeAnimatables = [];
  23450. }
  23451. };
  23452. Scene.prototype._animate = function () {
  23453. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23454. return;
  23455. }
  23456. // Getting time
  23457. var now = BABYLON.Tools.Now;
  23458. if (!this._animationTimeLast) {
  23459. if (this._pendingData.length > 0) {
  23460. return;
  23461. }
  23462. this._animationTimeLast = now;
  23463. }
  23464. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23465. this._animationTime += deltaTime;
  23466. this._animationTimeLast = now;
  23467. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23468. this._activeAnimatables[index]._animate(this._animationTime);
  23469. }
  23470. // Late animation bindings
  23471. this._processLateAnimationBindings();
  23472. };
  23473. /** @ignore */
  23474. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23475. var target = runtimeAnimation.target;
  23476. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23477. if (!target._lateAnimationHolders) {
  23478. target._lateAnimationHolders = {};
  23479. }
  23480. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23481. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23482. totalWeight: 0,
  23483. animations: []
  23484. };
  23485. }
  23486. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23487. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23488. };
  23489. Scene.prototype._processLateAnimationBindings = function () {
  23490. if (!this._registeredForLateAnimationBindings.length) {
  23491. return;
  23492. }
  23493. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23494. var target = this._registeredForLateAnimationBindings.data[index];
  23495. for (var path in target._lateAnimationHolders) {
  23496. var holder = target._lateAnimationHolders[path];
  23497. // Sanity check
  23498. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23499. continue;
  23500. }
  23501. var normalizer = 1.0;
  23502. var finalValue = void 0;
  23503. if (holder.totalWeight < 1.0) {
  23504. // We need to mix the original value in
  23505. var originalValue = holder.animations[0].originalValue;
  23506. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23507. }
  23508. else {
  23509. // We need to normalize the weights
  23510. normalizer = holder.totalWeight;
  23511. }
  23512. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23513. var runtimeAnimation = holder.animations[animIndex];
  23514. if (finalValue) {
  23515. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23516. }
  23517. else {
  23518. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23519. }
  23520. }
  23521. runtimeAnimation.target[path] = finalValue;
  23522. }
  23523. target._lateAnimationHolders = {};
  23524. }
  23525. this._registeredForLateAnimationBindings.reset();
  23526. };
  23527. // Matrix
  23528. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23529. this._useAlternateCameraConfiguration = active;
  23530. };
  23531. Scene.prototype.getViewMatrix = function () {
  23532. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23533. };
  23534. Scene.prototype.getProjectionMatrix = function () {
  23535. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23536. };
  23537. Scene.prototype.getTransformMatrix = function () {
  23538. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23539. };
  23540. Scene.prototype.setTransformMatrix = function (view, projection) {
  23541. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23542. return;
  23543. }
  23544. this._viewUpdateFlag = view.updateFlag;
  23545. this._projectionUpdateFlag = projection.updateFlag;
  23546. this._viewMatrix = view;
  23547. this._projectionMatrix = projection;
  23548. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23549. // Update frustum
  23550. if (!this._frustumPlanes) {
  23551. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23552. }
  23553. else {
  23554. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23555. }
  23556. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23557. var otherCamera = this.activeCamera._alternateCamera;
  23558. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23559. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23560. }
  23561. if (this._sceneUbo.useUbo) {
  23562. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23563. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23564. this._sceneUbo.update();
  23565. }
  23566. };
  23567. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23568. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23569. return;
  23570. }
  23571. this._alternateViewUpdateFlag = view.updateFlag;
  23572. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23573. this._alternateViewMatrix = view;
  23574. this._alternateProjectionMatrix = projection;
  23575. if (!this._alternateTransformMatrix) {
  23576. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23577. }
  23578. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23579. if (!this._alternateSceneUbo) {
  23580. this._createAlternateUbo();
  23581. }
  23582. if (this._alternateSceneUbo.useUbo) {
  23583. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23584. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23585. this._alternateSceneUbo.update();
  23586. }
  23587. };
  23588. Scene.prototype.getSceneUniformBuffer = function () {
  23589. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23590. };
  23591. // Methods
  23592. Scene.prototype.getUniqueId = function () {
  23593. var result = Scene._uniqueIdCounter;
  23594. Scene._uniqueIdCounter++;
  23595. return result;
  23596. };
  23597. Scene.prototype.addMesh = function (newMesh) {
  23598. this.meshes.push(newMesh);
  23599. //notify the collision coordinator
  23600. if (this.collisionCoordinator) {
  23601. this.collisionCoordinator.onMeshAdded(newMesh);
  23602. }
  23603. newMesh._resyncLightSources();
  23604. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23605. };
  23606. Scene.prototype.removeMesh = function (toRemove) {
  23607. var index = this.meshes.indexOf(toRemove);
  23608. if (index !== -1) {
  23609. // Remove from the scene if mesh found
  23610. this.meshes.splice(index, 1);
  23611. }
  23612. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23613. return index;
  23614. };
  23615. Scene.prototype.addTransformNode = function (newTransformNode) {
  23616. this.transformNodes.push(newTransformNode);
  23617. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23618. };
  23619. Scene.prototype.removeTransformNode = function (toRemove) {
  23620. var index = this.transformNodes.indexOf(toRemove);
  23621. if (index !== -1) {
  23622. // Remove from the scene if found
  23623. this.transformNodes.splice(index, 1);
  23624. }
  23625. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23626. return index;
  23627. };
  23628. Scene.prototype.removeSkeleton = function (toRemove) {
  23629. var index = this.skeletons.indexOf(toRemove);
  23630. if (index !== -1) {
  23631. // Remove from the scene if found
  23632. this.skeletons.splice(index, 1);
  23633. }
  23634. return index;
  23635. };
  23636. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23637. var index = this.morphTargetManagers.indexOf(toRemove);
  23638. if (index !== -1) {
  23639. // Remove from the scene if found
  23640. this.morphTargetManagers.splice(index, 1);
  23641. }
  23642. return index;
  23643. };
  23644. Scene.prototype.removeLight = function (toRemove) {
  23645. var index = this.lights.indexOf(toRemove);
  23646. if (index !== -1) {
  23647. // Remove from meshes
  23648. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23649. var mesh = _a[_i];
  23650. mesh._removeLightSource(toRemove);
  23651. }
  23652. // Remove from the scene if mesh found
  23653. this.lights.splice(index, 1);
  23654. this.sortLightsByPriority();
  23655. }
  23656. this.onLightRemovedObservable.notifyObservers(toRemove);
  23657. return index;
  23658. };
  23659. Scene.prototype.removeCamera = function (toRemove) {
  23660. var index = this.cameras.indexOf(toRemove);
  23661. if (index !== -1) {
  23662. // Remove from the scene if mesh found
  23663. this.cameras.splice(index, 1);
  23664. }
  23665. // Remove from activeCameras
  23666. var index2 = this.activeCameras.indexOf(toRemove);
  23667. if (index2 !== -1) {
  23668. // Remove from the scene if mesh found
  23669. this.activeCameras.splice(index2, 1);
  23670. }
  23671. // Reset the activeCamera
  23672. if (this.activeCamera === toRemove) {
  23673. if (this.cameras.length > 0) {
  23674. this.activeCamera = this.cameras[0];
  23675. }
  23676. else {
  23677. this.activeCamera = null;
  23678. }
  23679. }
  23680. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23681. return index;
  23682. };
  23683. Scene.prototype.removeParticleSystem = function (toRemove) {
  23684. var index = this.particleSystems.indexOf(toRemove);
  23685. if (index !== -1) {
  23686. this.particleSystems.splice(index, 1);
  23687. }
  23688. return index;
  23689. };
  23690. ;
  23691. Scene.prototype.removeAnimation = function (toRemove) {
  23692. var index = this.animations.indexOf(toRemove);
  23693. if (index !== -1) {
  23694. this.animations.splice(index, 1);
  23695. }
  23696. return index;
  23697. };
  23698. ;
  23699. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23700. var index = this.multiMaterials.indexOf(toRemove);
  23701. if (index !== -1) {
  23702. this.multiMaterials.splice(index, 1);
  23703. }
  23704. return index;
  23705. };
  23706. ;
  23707. Scene.prototype.removeMaterial = function (toRemove) {
  23708. var index = this.materials.indexOf(toRemove);
  23709. if (index !== -1) {
  23710. this.materials.splice(index, 1);
  23711. }
  23712. return index;
  23713. };
  23714. ;
  23715. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23716. var index = this.lensFlareSystems.indexOf(toRemove);
  23717. if (index !== -1) {
  23718. this.lensFlareSystems.splice(index, 1);
  23719. }
  23720. return index;
  23721. };
  23722. ;
  23723. Scene.prototype.removeActionManager = function (toRemove) {
  23724. var index = this._actionManagers.indexOf(toRemove);
  23725. if (index !== -1) {
  23726. this._actionManagers.splice(index, 1);
  23727. }
  23728. return index;
  23729. };
  23730. ;
  23731. Scene.prototype.addLight = function (newLight) {
  23732. this.lights.push(newLight);
  23733. this.sortLightsByPriority();
  23734. // Add light to all meshes (To support if the light is removed and then readded)
  23735. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23736. var mesh = _a[_i];
  23737. if (mesh._lightSources.indexOf(newLight) === -1) {
  23738. mesh._lightSources.push(newLight);
  23739. mesh._resyncLightSources();
  23740. }
  23741. }
  23742. this.onNewLightAddedObservable.notifyObservers(newLight);
  23743. };
  23744. Scene.prototype.sortLightsByPriority = function () {
  23745. if (this.requireLightSorting) {
  23746. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23747. }
  23748. };
  23749. Scene.prototype.addCamera = function (newCamera) {
  23750. this.cameras.push(newCamera);
  23751. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23752. };
  23753. Scene.prototype.addSkeleton = function (newSkeleton) {
  23754. this.skeletons.push(newSkeleton);
  23755. };
  23756. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23757. this.particleSystems.push(newParticleSystem);
  23758. };
  23759. Scene.prototype.addAnimation = function (newAnimation) {
  23760. this.animations.push(newAnimation);
  23761. };
  23762. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23763. this.multiMaterials.push(newMultiMaterial);
  23764. };
  23765. Scene.prototype.addMaterial = function (newMaterial) {
  23766. this.materials.push(newMaterial);
  23767. };
  23768. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23769. this.morphTargetManagers.push(newMorphTargetManager);
  23770. };
  23771. Scene.prototype.addGeometry = function (newGeometrie) {
  23772. this._geometries.push(newGeometrie);
  23773. };
  23774. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23775. this.lensFlareSystems.push(newLensFlareSystem);
  23776. };
  23777. Scene.prototype.addActionManager = function (newActionManager) {
  23778. this._actionManagers.push(newActionManager);
  23779. };
  23780. /**
  23781. * Switch active camera
  23782. * @param {Camera} newCamera - new active camera
  23783. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23784. */
  23785. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23786. if (attachControl === void 0) { attachControl = true; }
  23787. var canvas = this._engine.getRenderingCanvas();
  23788. if (!canvas) {
  23789. return;
  23790. }
  23791. if (this.activeCamera) {
  23792. this.activeCamera.detachControl(canvas);
  23793. }
  23794. this.activeCamera = newCamera;
  23795. if (attachControl) {
  23796. newCamera.attachControl(canvas);
  23797. }
  23798. };
  23799. /**
  23800. * sets the active camera of the scene using its ID
  23801. * @param {string} id - the camera's ID
  23802. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23803. * @see activeCamera
  23804. */
  23805. Scene.prototype.setActiveCameraByID = function (id) {
  23806. var camera = this.getCameraByID(id);
  23807. if (camera) {
  23808. this.activeCamera = camera;
  23809. return camera;
  23810. }
  23811. return null;
  23812. };
  23813. /**
  23814. * sets the active camera of the scene using its name
  23815. * @param {string} name - the camera's name
  23816. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23817. * @see activeCamera
  23818. */
  23819. Scene.prototype.setActiveCameraByName = function (name) {
  23820. var camera = this.getCameraByName(name);
  23821. if (camera) {
  23822. this.activeCamera = camera;
  23823. return camera;
  23824. }
  23825. return null;
  23826. };
  23827. /**
  23828. * get an animation group using its name
  23829. * @param {string} the material's name
  23830. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23831. */
  23832. Scene.prototype.getAnimationGroupByName = function (name) {
  23833. for (var index = 0; index < this.animationGroups.length; index++) {
  23834. if (this.animationGroups[index].name === name) {
  23835. return this.animationGroups[index];
  23836. }
  23837. }
  23838. return null;
  23839. };
  23840. /**
  23841. * get a material using its id
  23842. * @param {string} the material's ID
  23843. * @return {BABYLON.Material|null} the material or null if none found.
  23844. */
  23845. Scene.prototype.getMaterialByID = function (id) {
  23846. for (var index = 0; index < this.materials.length; index++) {
  23847. if (this.materials[index].id === id) {
  23848. return this.materials[index];
  23849. }
  23850. }
  23851. return null;
  23852. };
  23853. /**
  23854. * get a material using its name
  23855. * @param {string} the material's name
  23856. * @return {BABYLON.Material|null} the material or null if none found.
  23857. */
  23858. Scene.prototype.getMaterialByName = function (name) {
  23859. for (var index = 0; index < this.materials.length; index++) {
  23860. if (this.materials[index].name === name) {
  23861. return this.materials[index];
  23862. }
  23863. }
  23864. return null;
  23865. };
  23866. Scene.prototype.getLensFlareSystemByName = function (name) {
  23867. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23868. if (this.lensFlareSystems[index].name === name) {
  23869. return this.lensFlareSystems[index];
  23870. }
  23871. }
  23872. return null;
  23873. };
  23874. Scene.prototype.getLensFlareSystemByID = function (id) {
  23875. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23876. if (this.lensFlareSystems[index].id === id) {
  23877. return this.lensFlareSystems[index];
  23878. }
  23879. }
  23880. return null;
  23881. };
  23882. Scene.prototype.getCameraByID = function (id) {
  23883. for (var index = 0; index < this.cameras.length; index++) {
  23884. if (this.cameras[index].id === id) {
  23885. return this.cameras[index];
  23886. }
  23887. }
  23888. return null;
  23889. };
  23890. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23891. for (var index = 0; index < this.cameras.length; index++) {
  23892. if (this.cameras[index].uniqueId === uniqueId) {
  23893. return this.cameras[index];
  23894. }
  23895. }
  23896. return null;
  23897. };
  23898. /**
  23899. * get a camera using its name
  23900. * @param {string} the camera's name
  23901. * @return {BABYLON.Camera|null} the camera or null if none found.
  23902. */
  23903. Scene.prototype.getCameraByName = function (name) {
  23904. for (var index = 0; index < this.cameras.length; index++) {
  23905. if (this.cameras[index].name === name) {
  23906. return this.cameras[index];
  23907. }
  23908. }
  23909. return null;
  23910. };
  23911. /**
  23912. * get a bone using its id
  23913. * @param {string} the bone's id
  23914. * @return {BABYLON.Bone|null} the bone or null if not found
  23915. */
  23916. Scene.prototype.getBoneByID = function (id) {
  23917. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23918. var skeleton = this.skeletons[skeletonIndex];
  23919. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23920. if (skeleton.bones[boneIndex].id === id) {
  23921. return skeleton.bones[boneIndex];
  23922. }
  23923. }
  23924. }
  23925. return null;
  23926. };
  23927. /**
  23928. * get a bone using its id
  23929. * @param {string} the bone's name
  23930. * @return {BABYLON.Bone|null} the bone or null if not found
  23931. */
  23932. Scene.prototype.getBoneByName = function (name) {
  23933. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23934. var skeleton = this.skeletons[skeletonIndex];
  23935. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23936. if (skeleton.bones[boneIndex].name === name) {
  23937. return skeleton.bones[boneIndex];
  23938. }
  23939. }
  23940. }
  23941. return null;
  23942. };
  23943. /**
  23944. * get a light node using its name
  23945. * @param {string} the light's name
  23946. * @return {BABYLON.Light|null} the light or null if none found.
  23947. */
  23948. Scene.prototype.getLightByName = function (name) {
  23949. for (var index = 0; index < this.lights.length; index++) {
  23950. if (this.lights[index].name === name) {
  23951. return this.lights[index];
  23952. }
  23953. }
  23954. return null;
  23955. };
  23956. /**
  23957. * get a light node using its ID
  23958. * @param {string} the light's id
  23959. * @return {BABYLON.Light|null} the light or null if none found.
  23960. */
  23961. Scene.prototype.getLightByID = function (id) {
  23962. for (var index = 0; index < this.lights.length; index++) {
  23963. if (this.lights[index].id === id) {
  23964. return this.lights[index];
  23965. }
  23966. }
  23967. return null;
  23968. };
  23969. /**
  23970. * get a light node using its scene-generated unique ID
  23971. * @param {number} the light's unique id
  23972. * @return {BABYLON.Light|null} the light or null if none found.
  23973. */
  23974. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23975. for (var index = 0; index < this.lights.length; index++) {
  23976. if (this.lights[index].uniqueId === uniqueId) {
  23977. return this.lights[index];
  23978. }
  23979. }
  23980. return null;
  23981. };
  23982. /**
  23983. * get a particle system by id
  23984. * @param id {number} the particle system id
  23985. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23986. */
  23987. Scene.prototype.getParticleSystemByID = function (id) {
  23988. for (var index = 0; index < this.particleSystems.length; index++) {
  23989. if (this.particleSystems[index].id === id) {
  23990. return this.particleSystems[index];
  23991. }
  23992. }
  23993. return null;
  23994. };
  23995. /**
  23996. * get a geometry using its ID
  23997. * @param {string} the geometry's id
  23998. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23999. */
  24000. Scene.prototype.getGeometryByID = function (id) {
  24001. for (var index = 0; index < this._geometries.length; index++) {
  24002. if (this._geometries[index].id === id) {
  24003. return this._geometries[index];
  24004. }
  24005. }
  24006. return null;
  24007. };
  24008. /**
  24009. * add a new geometry to this scene.
  24010. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24011. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24012. * @return {boolean} was the geometry added or not
  24013. */
  24014. Scene.prototype.pushGeometry = function (geometry, force) {
  24015. if (!force && this.getGeometryByID(geometry.id)) {
  24016. return false;
  24017. }
  24018. this._geometries.push(geometry);
  24019. //notify the collision coordinator
  24020. if (this.collisionCoordinator) {
  24021. this.collisionCoordinator.onGeometryAdded(geometry);
  24022. }
  24023. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24024. return true;
  24025. };
  24026. /**
  24027. * Removes an existing geometry
  24028. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24029. * @return {boolean} was the geometry removed or not
  24030. */
  24031. Scene.prototype.removeGeometry = function (geometry) {
  24032. var index = this._geometries.indexOf(geometry);
  24033. if (index > -1) {
  24034. this._geometries.splice(index, 1);
  24035. //notify the collision coordinator
  24036. if (this.collisionCoordinator) {
  24037. this.collisionCoordinator.onGeometryDeleted(geometry);
  24038. }
  24039. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24040. return true;
  24041. }
  24042. return false;
  24043. };
  24044. Scene.prototype.getGeometries = function () {
  24045. return this._geometries;
  24046. };
  24047. /**
  24048. * Get the first added mesh found of a given ID
  24049. * @param {string} id - the id to search for
  24050. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24051. */
  24052. Scene.prototype.getMeshByID = function (id) {
  24053. for (var index = 0; index < this.meshes.length; index++) {
  24054. if (this.meshes[index].id === id) {
  24055. return this.meshes[index];
  24056. }
  24057. }
  24058. return null;
  24059. };
  24060. Scene.prototype.getMeshesByID = function (id) {
  24061. return this.meshes.filter(function (m) {
  24062. return m.id === id;
  24063. });
  24064. };
  24065. /**
  24066. * Get the first added transform node found of a given ID
  24067. * @param {string} id - the id to search for
  24068. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24069. */
  24070. Scene.prototype.getTransformNodeByID = function (id) {
  24071. for (var index = 0; index < this.transformNodes.length; index++) {
  24072. if (this.transformNodes[index].id === id) {
  24073. return this.transformNodes[index];
  24074. }
  24075. }
  24076. return null;
  24077. };
  24078. Scene.prototype.getTransformNodesByID = function (id) {
  24079. return this.transformNodes.filter(function (m) {
  24080. return m.id === id;
  24081. });
  24082. };
  24083. /**
  24084. * Get a mesh with its auto-generated unique id
  24085. * @param {number} uniqueId - the unique id to search for
  24086. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24087. */
  24088. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24089. for (var index = 0; index < this.meshes.length; index++) {
  24090. if (this.meshes[index].uniqueId === uniqueId) {
  24091. return this.meshes[index];
  24092. }
  24093. }
  24094. return null;
  24095. };
  24096. /**
  24097. * Get a the last added mesh found of a given ID
  24098. * @param {string} id - the id to search for
  24099. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24100. */
  24101. Scene.prototype.getLastMeshByID = function (id) {
  24102. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24103. if (this.meshes[index].id === id) {
  24104. return this.meshes[index];
  24105. }
  24106. }
  24107. return null;
  24108. };
  24109. /**
  24110. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24111. * @param {string} id - the id to search for
  24112. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24113. */
  24114. Scene.prototype.getLastEntryByID = function (id) {
  24115. var index;
  24116. for (index = this.meshes.length - 1; index >= 0; index--) {
  24117. if (this.meshes[index].id === id) {
  24118. return this.meshes[index];
  24119. }
  24120. }
  24121. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24122. if (this.transformNodes[index].id === id) {
  24123. return this.transformNodes[index];
  24124. }
  24125. }
  24126. for (index = this.cameras.length - 1; index >= 0; index--) {
  24127. if (this.cameras[index].id === id) {
  24128. return this.cameras[index];
  24129. }
  24130. }
  24131. for (index = this.lights.length - 1; index >= 0; index--) {
  24132. if (this.lights[index].id === id) {
  24133. return this.lights[index];
  24134. }
  24135. }
  24136. return null;
  24137. };
  24138. Scene.prototype.getNodeByID = function (id) {
  24139. var mesh = this.getMeshByID(id);
  24140. if (mesh) {
  24141. return mesh;
  24142. }
  24143. var light = this.getLightByID(id);
  24144. if (light) {
  24145. return light;
  24146. }
  24147. var camera = this.getCameraByID(id);
  24148. if (camera) {
  24149. return camera;
  24150. }
  24151. var bone = this.getBoneByID(id);
  24152. return bone;
  24153. };
  24154. Scene.prototype.getNodeByName = function (name) {
  24155. var mesh = this.getMeshByName(name);
  24156. if (mesh) {
  24157. return mesh;
  24158. }
  24159. var light = this.getLightByName(name);
  24160. if (light) {
  24161. return light;
  24162. }
  24163. var camera = this.getCameraByName(name);
  24164. if (camera) {
  24165. return camera;
  24166. }
  24167. var bone = this.getBoneByName(name);
  24168. return bone;
  24169. };
  24170. Scene.prototype.getMeshByName = function (name) {
  24171. for (var index = 0; index < this.meshes.length; index++) {
  24172. if (this.meshes[index].name === name) {
  24173. return this.meshes[index];
  24174. }
  24175. }
  24176. return null;
  24177. };
  24178. Scene.prototype.getTransformNodeByName = function (name) {
  24179. for (var index = 0; index < this.transformNodes.length; index++) {
  24180. if (this.transformNodes[index].name === name) {
  24181. return this.transformNodes[index];
  24182. }
  24183. }
  24184. return null;
  24185. };
  24186. Scene.prototype.getSoundByName = function (name) {
  24187. var index;
  24188. if (BABYLON.AudioEngine) {
  24189. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24190. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24191. return this.mainSoundTrack.soundCollection[index];
  24192. }
  24193. }
  24194. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24195. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24196. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24197. return this.soundTracks[sdIndex].soundCollection[index];
  24198. }
  24199. }
  24200. }
  24201. }
  24202. return null;
  24203. };
  24204. Scene.prototype.getLastSkeletonByID = function (id) {
  24205. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24206. if (this.skeletons[index].id === id) {
  24207. return this.skeletons[index];
  24208. }
  24209. }
  24210. return null;
  24211. };
  24212. Scene.prototype.getSkeletonById = function (id) {
  24213. for (var index = 0; index < this.skeletons.length; index++) {
  24214. if (this.skeletons[index].id === id) {
  24215. return this.skeletons[index];
  24216. }
  24217. }
  24218. return null;
  24219. };
  24220. Scene.prototype.getSkeletonByName = function (name) {
  24221. for (var index = 0; index < this.skeletons.length; index++) {
  24222. if (this.skeletons[index].name === name) {
  24223. return this.skeletons[index];
  24224. }
  24225. }
  24226. return null;
  24227. };
  24228. Scene.prototype.getMorphTargetManagerById = function (id) {
  24229. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24230. if (this.morphTargetManagers[index].uniqueId === id) {
  24231. return this.morphTargetManagers[index];
  24232. }
  24233. }
  24234. return null;
  24235. };
  24236. Scene.prototype.isActiveMesh = function (mesh) {
  24237. return (this._activeMeshes.indexOf(mesh) !== -1);
  24238. };
  24239. /**
  24240. * Return a the first highlight layer of the scene with a given name.
  24241. * @param name The name of the highlight layer to look for.
  24242. * @return The highlight layer if found otherwise null.
  24243. */
  24244. Scene.prototype.getHighlightLayerByName = function (name) {
  24245. for (var index = 0; index < this.effectLayers.length; index++) {
  24246. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24247. return this.effectLayers[index];
  24248. }
  24249. }
  24250. return null;
  24251. };
  24252. /**
  24253. * Return a the first highlight layer of the scene with a given name.
  24254. * @param name The name of the highlight layer to look for.
  24255. * @return The highlight layer if found otherwise null.
  24256. */
  24257. Scene.prototype.getGlowLayerByName = function (name) {
  24258. for (var index = 0; index < this.effectLayers.length; index++) {
  24259. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24260. return this.effectLayers[index];
  24261. }
  24262. }
  24263. return null;
  24264. };
  24265. Object.defineProperty(Scene.prototype, "uid", {
  24266. /**
  24267. * Return a unique id as a string which can serve as an identifier for the scene
  24268. */
  24269. get: function () {
  24270. if (!this._uid) {
  24271. this._uid = BABYLON.Tools.RandomId();
  24272. }
  24273. return this._uid;
  24274. },
  24275. enumerable: true,
  24276. configurable: true
  24277. });
  24278. /**
  24279. * Add an externaly attached data from its key.
  24280. * This method call will fail and return false, if such key already exists.
  24281. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24282. * @param key the unique key that identifies the data
  24283. * @param data the data object to associate to the key for this Engine instance
  24284. * @return true if no such key were already present and the data was added successfully, false otherwise
  24285. */
  24286. Scene.prototype.addExternalData = function (key, data) {
  24287. if (!this._externalData) {
  24288. this._externalData = new BABYLON.StringDictionary();
  24289. }
  24290. return this._externalData.add(key, data);
  24291. };
  24292. /**
  24293. * Get an externaly attached data from its key
  24294. * @param key the unique key that identifies the data
  24295. * @return the associated data, if present (can be null), or undefined if not present
  24296. */
  24297. Scene.prototype.getExternalData = function (key) {
  24298. if (!this._externalData) {
  24299. return null;
  24300. }
  24301. return this._externalData.get(key);
  24302. };
  24303. /**
  24304. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24305. * @param key the unique key that identifies the data
  24306. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24307. * @return the associated data, can be null if the factory returned null.
  24308. */
  24309. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24310. if (!this._externalData) {
  24311. this._externalData = new BABYLON.StringDictionary();
  24312. }
  24313. return this._externalData.getOrAddWithFactory(key, factory);
  24314. };
  24315. /**
  24316. * Remove an externaly attached data from the Engine instance
  24317. * @param key the unique key that identifies the data
  24318. * @return true if the data was successfully removed, false if it doesn't exist
  24319. */
  24320. Scene.prototype.removeExternalData = function (key) {
  24321. return this._externalData.remove(key);
  24322. };
  24323. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24324. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24325. if (mesh.showSubMeshesBoundingBox) {
  24326. var boundingInfo = subMesh.getBoundingInfo();
  24327. if (boundingInfo !== null && boundingInfo !== undefined) {
  24328. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24329. }
  24330. }
  24331. var material = subMesh.getMaterial();
  24332. if (material !== null && material !== undefined) {
  24333. // Render targets
  24334. if (material.getRenderTargetTextures !== undefined) {
  24335. if (this._processedMaterials.indexOf(material) === -1) {
  24336. this._processedMaterials.push(material);
  24337. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24338. }
  24339. }
  24340. // Dispatch
  24341. this._activeIndices.addCount(subMesh.indexCount, false);
  24342. this._renderingManager.dispatch(subMesh, mesh, material);
  24343. }
  24344. }
  24345. };
  24346. /**
  24347. * Clear the processed materials smart array preventing retention point in material dispose.
  24348. */
  24349. Scene.prototype.freeProcessedMaterials = function () {
  24350. this._processedMaterials.dispose();
  24351. };
  24352. /**
  24353. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24354. */
  24355. Scene.prototype.freeActiveMeshes = function () {
  24356. this._activeMeshes.dispose();
  24357. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24358. this.activeCamera._activeMeshes.dispose();
  24359. }
  24360. if (this.activeCameras) {
  24361. for (var i = 0; i < this.activeCameras.length; i++) {
  24362. var activeCamera = this.activeCameras[i];
  24363. if (activeCamera && activeCamera._activeMeshes) {
  24364. activeCamera._activeMeshes.dispose();
  24365. }
  24366. }
  24367. }
  24368. };
  24369. /**
  24370. * Clear the info related to rendering groups preventing retention points during dispose.
  24371. */
  24372. Scene.prototype.freeRenderingGroups = function () {
  24373. if (this._renderingManager) {
  24374. this._renderingManager.freeRenderingGroups();
  24375. }
  24376. if (this.textures) {
  24377. for (var i = 0; i < this.textures.length; i++) {
  24378. var texture = this.textures[i];
  24379. if (texture && texture.renderList) {
  24380. texture.freeRenderingGroups();
  24381. }
  24382. }
  24383. }
  24384. };
  24385. Scene.prototype._isInIntermediateRendering = function () {
  24386. return this._intermediateRendering;
  24387. };
  24388. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24389. this._activeMeshCandidateProvider = provider;
  24390. };
  24391. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24392. return this._activeMeshCandidateProvider;
  24393. };
  24394. /**
  24395. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24396. */
  24397. Scene.prototype.freezeActiveMeshes = function () {
  24398. if (!this.activeCamera) {
  24399. return this;
  24400. }
  24401. if (!this._frustumPlanes) {
  24402. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24403. }
  24404. this._evaluateActiveMeshes();
  24405. this._activeMeshesFrozen = true;
  24406. return this;
  24407. };
  24408. /**
  24409. * Use this function to restart evaluating active meshes on every frame
  24410. */
  24411. Scene.prototype.unfreezeActiveMeshes = function () {
  24412. this._activeMeshesFrozen = false;
  24413. return this;
  24414. };
  24415. Scene.prototype._evaluateActiveMeshes = function () {
  24416. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24417. return;
  24418. }
  24419. if (!this.activeCamera) {
  24420. return;
  24421. }
  24422. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24423. this.activeCamera._activeMeshes.reset();
  24424. this._activeMeshes.reset();
  24425. this._renderingManager.reset();
  24426. this._processedMaterials.reset();
  24427. this._activeParticleSystems.reset();
  24428. this._activeSkeletons.reset();
  24429. this._softwareSkinnedMeshes.reset();
  24430. if (this._boundingBoxRenderer) {
  24431. this._boundingBoxRenderer.reset();
  24432. }
  24433. // Meshes
  24434. var meshes;
  24435. var len;
  24436. var checkIsEnabled = true;
  24437. // Determine mesh candidates
  24438. if (this._activeMeshCandidateProvider !== undefined) {
  24439. // Use _activeMeshCandidateProvider
  24440. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24441. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24442. if (meshes !== undefined) {
  24443. len = meshes.length;
  24444. }
  24445. else {
  24446. len = 0;
  24447. }
  24448. }
  24449. else if (this._selectionOctree !== undefined) {
  24450. // Octree
  24451. var selection = this._selectionOctree.select(this._frustumPlanes);
  24452. meshes = selection.data;
  24453. len = selection.length;
  24454. }
  24455. else {
  24456. // Full scene traversal
  24457. len = this.meshes.length;
  24458. meshes = this.meshes;
  24459. }
  24460. // Check each mesh
  24461. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24462. mesh = meshes[meshIndex];
  24463. if (mesh.isBlocked) {
  24464. continue;
  24465. }
  24466. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24467. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24468. continue;
  24469. }
  24470. mesh.computeWorldMatrix();
  24471. // Intersections
  24472. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24473. this._meshesForIntersections.pushNoDuplicate(mesh);
  24474. }
  24475. // Switch to current LOD
  24476. meshLOD = mesh.getLOD(this.activeCamera);
  24477. if (meshLOD === undefined || meshLOD === null) {
  24478. continue;
  24479. }
  24480. mesh._preActivate();
  24481. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24482. this._activeMeshes.push(mesh);
  24483. this.activeCamera._activeMeshes.push(mesh);
  24484. mesh._activate(this._renderId);
  24485. if (meshLOD !== mesh) {
  24486. meshLOD._activate(this._renderId);
  24487. }
  24488. this._activeMesh(mesh, meshLOD);
  24489. }
  24490. }
  24491. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24492. // Particle systems
  24493. if (this.particlesEnabled) {
  24494. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24495. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24496. var particleSystem = this.particleSystems[particleIndex];
  24497. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24498. continue;
  24499. }
  24500. var emitter = particleSystem.emitter;
  24501. if (!emitter.position || emitter.isEnabled()) {
  24502. this._activeParticleSystems.push(particleSystem);
  24503. particleSystem.animate();
  24504. this._renderingManager.dispatchParticles(particleSystem);
  24505. }
  24506. }
  24507. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24508. }
  24509. };
  24510. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24511. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24512. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24513. mesh.skeleton.prepare();
  24514. }
  24515. if (!mesh.computeBonesUsingShaders) {
  24516. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24517. }
  24518. }
  24519. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24520. var boundingInfo = sourceMesh.getBoundingInfo();
  24521. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24522. }
  24523. if (mesh !== undefined && mesh !== null
  24524. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24525. // Submeshes Octrees
  24526. var len;
  24527. var subMeshes;
  24528. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24529. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24530. len = intersections.length;
  24531. subMeshes = intersections.data;
  24532. }
  24533. else {
  24534. subMeshes = mesh.subMeshes;
  24535. len = subMeshes.length;
  24536. }
  24537. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24538. subMesh = subMeshes[subIndex];
  24539. this._evaluateSubMesh(subMesh, mesh);
  24540. }
  24541. }
  24542. };
  24543. Scene.prototype.updateTransformMatrix = function (force) {
  24544. if (!this.activeCamera) {
  24545. return;
  24546. }
  24547. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24548. };
  24549. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24550. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24551. };
  24552. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24553. if (camera && camera._skipRendering) {
  24554. return;
  24555. }
  24556. var engine = this._engine;
  24557. this.activeCamera = camera;
  24558. if (!this.activeCamera)
  24559. throw new Error("Active camera not set");
  24560. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24561. // Viewport
  24562. engine.setViewport(this.activeCamera.viewport);
  24563. // Camera
  24564. this.resetCachedMaterial();
  24565. this._renderId++;
  24566. this.updateTransformMatrix();
  24567. if (camera._alternateCamera) {
  24568. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24569. this._alternateRendering = true;
  24570. }
  24571. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24572. // Meshes
  24573. this._evaluateActiveMeshes();
  24574. // Software skinning
  24575. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24576. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24577. mesh.applySkeleton(mesh.skeleton);
  24578. }
  24579. // Render targets
  24580. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24581. var needsRestoreFrameBuffer = false;
  24582. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24583. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24584. }
  24585. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24586. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24587. }
  24588. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24589. this._intermediateRendering = true;
  24590. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24591. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24592. var renderTarget = this._renderTargets.data[renderIndex];
  24593. if (renderTarget._shouldRender()) {
  24594. this._renderId++;
  24595. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24596. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24597. }
  24598. }
  24599. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24600. this._intermediateRendering = false;
  24601. this._renderId++;
  24602. needsRestoreFrameBuffer = true; // Restore back buffer
  24603. }
  24604. // Render EffecttLayer Texture
  24605. var stencilState = this._engine.getStencilBuffer();
  24606. var renderEffects = false;
  24607. var needStencil = false;
  24608. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24609. this._intermediateRendering = true;
  24610. for (var i = 0; i < this.effectLayers.length; i++) {
  24611. var effectLayer = this.effectLayers[i];
  24612. if (effectLayer.shouldRender() &&
  24613. (!effectLayer.camera ||
  24614. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24615. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24616. renderEffects = true;
  24617. needStencil = needStencil || effectLayer.needStencil();
  24618. var renderTarget = effectLayer._mainTexture;
  24619. if (renderTarget._shouldRender()) {
  24620. this._renderId++;
  24621. renderTarget.render(false, false);
  24622. needsRestoreFrameBuffer = true;
  24623. }
  24624. }
  24625. }
  24626. this._intermediateRendering = false;
  24627. this._renderId++;
  24628. }
  24629. if (needsRestoreFrameBuffer) {
  24630. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24631. }
  24632. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24633. // Prepare Frame
  24634. this.postProcessManager._prepareFrame();
  24635. // Backgrounds
  24636. var layerIndex;
  24637. var layer;
  24638. if (this.layers.length) {
  24639. engine.setDepthBuffer(false);
  24640. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24641. layer = this.layers[layerIndex];
  24642. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24643. layer.render();
  24644. }
  24645. }
  24646. engine.setDepthBuffer(true);
  24647. }
  24648. // Activate effect Layer stencil
  24649. if (needStencil) {
  24650. this._engine.setStencilBuffer(true);
  24651. }
  24652. // Render
  24653. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24654. this._renderingManager.render(null, null, true, true);
  24655. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24656. // Restore effect Layer stencil
  24657. if (needStencil) {
  24658. this._engine.setStencilBuffer(stencilState);
  24659. }
  24660. // Bounding boxes
  24661. if (this._boundingBoxRenderer) {
  24662. this._boundingBoxRenderer.render();
  24663. }
  24664. // Lens flares
  24665. if (this.lensFlaresEnabled) {
  24666. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24667. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24668. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24669. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24670. lensFlareSystem.render();
  24671. }
  24672. }
  24673. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24674. }
  24675. // Foregrounds
  24676. if (this.layers.length) {
  24677. engine.setDepthBuffer(false);
  24678. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24679. layer = this.layers[layerIndex];
  24680. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24681. layer.render();
  24682. }
  24683. }
  24684. engine.setDepthBuffer(true);
  24685. }
  24686. // Effect Layer
  24687. if (renderEffects) {
  24688. engine.setDepthBuffer(false);
  24689. for (var i = 0; i < this.effectLayers.length; i++) {
  24690. if (this.effectLayers[i].shouldRender()) {
  24691. this.effectLayers[i].render();
  24692. }
  24693. }
  24694. engine.setDepthBuffer(true);
  24695. }
  24696. // Finalize frame
  24697. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24698. // Reset some special arrays
  24699. this._renderTargets.reset();
  24700. this._alternateRendering = false;
  24701. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24702. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24703. };
  24704. Scene.prototype._processSubCameras = function (camera) {
  24705. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24706. this._renderForCamera(camera);
  24707. return;
  24708. }
  24709. // rig cameras
  24710. for (var index = 0; index < camera._rigCameras.length; index++) {
  24711. this._renderForCamera(camera._rigCameras[index], camera);
  24712. }
  24713. this.activeCamera = camera;
  24714. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24715. };
  24716. Scene.prototype._checkIntersections = function () {
  24717. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24718. var sourceMesh = this._meshesForIntersections.data[index];
  24719. if (!sourceMesh.actionManager) {
  24720. continue;
  24721. }
  24722. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24723. var action = sourceMesh.actionManager.actions[actionIndex];
  24724. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24725. var parameters = action.getTriggerParameter();
  24726. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24727. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24728. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24729. if (areIntersecting && currentIntersectionInProgress === -1) {
  24730. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24731. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24732. sourceMesh._intersectionsInProgress.push(otherMesh);
  24733. }
  24734. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24735. sourceMesh._intersectionsInProgress.push(otherMesh);
  24736. }
  24737. }
  24738. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24739. //They intersected, and now they don't.
  24740. //is this trigger an exit trigger? execute an event.
  24741. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24742. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24743. }
  24744. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24745. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24746. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24747. }
  24748. }
  24749. }
  24750. }
  24751. }
  24752. };
  24753. Scene.prototype.render = function () {
  24754. if (this.isDisposed) {
  24755. return;
  24756. }
  24757. this._activeParticles.fetchNewFrame();
  24758. this._totalVertices.fetchNewFrame();
  24759. this._activeIndices.fetchNewFrame();
  24760. this._activeBones.fetchNewFrame();
  24761. this._meshesForIntersections.reset();
  24762. this.resetCachedMaterial();
  24763. this.onBeforeAnimationsObservable.notifyObservers(this);
  24764. // Actions
  24765. if (this.actionManager) {
  24766. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24767. }
  24768. //Simplification Queue
  24769. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24770. this.simplificationQueue.executeNext();
  24771. }
  24772. if (this._engine.isDeterministicLockStep()) {
  24773. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24774. var defaultFPS = (60.0 / 1000.0);
  24775. var defaultFrameTime = 1000 / 60; // frame time in MS
  24776. if (this._physicsEngine) {
  24777. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24778. }
  24779. var stepsTaken = 0;
  24780. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24781. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24782. internalSteps = Math.min(internalSteps, maxSubSteps);
  24783. do {
  24784. this.onBeforeStepObservable.notifyObservers(this);
  24785. // Animations
  24786. this._animationRatio = defaultFrameTime * defaultFPS;
  24787. this._animate();
  24788. this.onAfterAnimationsObservable.notifyObservers(this);
  24789. // Physics
  24790. if (this._physicsEngine) {
  24791. this.onBeforePhysicsObservable.notifyObservers(this);
  24792. this._physicsEngine._step(defaultFrameTime / 1000);
  24793. this.onAfterPhysicsObservable.notifyObservers(this);
  24794. }
  24795. this.onAfterStepObservable.notifyObservers(this);
  24796. this._currentStepId++;
  24797. stepsTaken++;
  24798. deltaTime -= defaultFrameTime;
  24799. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24800. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24801. }
  24802. else {
  24803. // Animations
  24804. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24805. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24806. this._animate();
  24807. this.onAfterAnimationsObservable.notifyObservers(this);
  24808. // Physics
  24809. if (this._physicsEngine) {
  24810. this.onBeforePhysicsObservable.notifyObservers(this);
  24811. this._physicsEngine._step(deltaTime / 1000.0);
  24812. this.onAfterPhysicsObservable.notifyObservers(this);
  24813. }
  24814. }
  24815. // update gamepad manager
  24816. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24817. this._gamepadManager._checkGamepadsStatus();
  24818. }
  24819. // Update Cameras
  24820. if (this.activeCameras.length > 0) {
  24821. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24822. var camera = this.activeCameras[cameraIndex];
  24823. camera.update();
  24824. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24825. // rig cameras
  24826. for (var index = 0; index < camera._rigCameras.length; index++) {
  24827. camera._rigCameras[index].update();
  24828. }
  24829. }
  24830. }
  24831. }
  24832. else if (this.activeCamera) {
  24833. this.activeCamera.update();
  24834. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24835. // rig cameras
  24836. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24837. this.activeCamera._rigCameras[index].update();
  24838. }
  24839. }
  24840. }
  24841. // Before render
  24842. this.onBeforeRenderObservable.notifyObservers(this);
  24843. // Customs render targets
  24844. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24845. var engine = this.getEngine();
  24846. var currentActiveCamera = this.activeCamera;
  24847. if (this.renderTargetsEnabled) {
  24848. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24849. this._intermediateRendering = true;
  24850. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24851. var renderTarget = this.customRenderTargets[customIndex];
  24852. if (renderTarget._shouldRender()) {
  24853. this._renderId++;
  24854. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24855. if (!this.activeCamera)
  24856. throw new Error("Active camera not set");
  24857. // Viewport
  24858. engine.setViewport(this.activeCamera.viewport);
  24859. // Camera
  24860. this.updateTransformMatrix();
  24861. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24862. }
  24863. }
  24864. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24865. this._intermediateRendering = false;
  24866. this._renderId++;
  24867. }
  24868. // Restore back buffer
  24869. if (this.customRenderTargets.length > 0) {
  24870. engine.restoreDefaultFramebuffer();
  24871. }
  24872. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24873. this.activeCamera = currentActiveCamera;
  24874. // Procedural textures
  24875. if (this.proceduralTexturesEnabled) {
  24876. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24877. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24878. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24879. if (proceduralTexture._shouldRender()) {
  24880. proceduralTexture.render();
  24881. }
  24882. }
  24883. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24884. }
  24885. // Clear
  24886. if (this.autoClearDepthAndStencil || this.autoClear) {
  24887. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24888. }
  24889. // Shadows
  24890. if (this.shadowsEnabled) {
  24891. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24892. var light = this.lights[lightIndex];
  24893. var shadowGenerator = light.getShadowGenerator();
  24894. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24895. var shadowMap = (shadowGenerator.getShadowMap());
  24896. if (this.textures.indexOf(shadowMap) !== -1) {
  24897. this._renderTargets.push(shadowMap);
  24898. }
  24899. }
  24900. }
  24901. }
  24902. // Depth renderer
  24903. for (var key in this._depthRenderer) {
  24904. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24905. }
  24906. // Geometry renderer
  24907. if (this._geometryBufferRenderer) {
  24908. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24909. }
  24910. // RenderPipeline
  24911. if (this._postProcessRenderPipelineManager) {
  24912. this._postProcessRenderPipelineManager.update();
  24913. }
  24914. // Multi-cameras?
  24915. if (this.activeCameras.length > 0) {
  24916. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24917. if (cameraIndex > 0) {
  24918. this._engine.clear(null, false, true, true);
  24919. }
  24920. this._processSubCameras(this.activeCameras[cameraIndex]);
  24921. }
  24922. }
  24923. else {
  24924. if (!this.activeCamera) {
  24925. throw new Error("No camera defined");
  24926. }
  24927. this._processSubCameras(this.activeCamera);
  24928. }
  24929. // Intersection checks
  24930. this._checkIntersections();
  24931. // Update the audio listener attached to the camera
  24932. if (BABYLON.AudioEngine) {
  24933. this._updateAudioParameters();
  24934. }
  24935. // After render
  24936. if (this.afterRender) {
  24937. this.afterRender();
  24938. }
  24939. this.onAfterRenderObservable.notifyObservers(this);
  24940. // Cleaning
  24941. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24942. var data = this._toBeDisposed.data[index];
  24943. if (data) {
  24944. data.dispose();
  24945. }
  24946. this._toBeDisposed[index] = null;
  24947. }
  24948. this._toBeDisposed.reset();
  24949. if (this.dumpNextRenderTargets) {
  24950. this.dumpNextRenderTargets = false;
  24951. }
  24952. this._activeBones.addCount(0, true);
  24953. this._activeIndices.addCount(0, true);
  24954. this._activeParticles.addCount(0, true);
  24955. };
  24956. Scene.prototype._updateAudioParameters = function () {
  24957. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24958. return;
  24959. }
  24960. var listeningCamera;
  24961. var audioEngine = BABYLON.Engine.audioEngine;
  24962. if (this.activeCameras.length > 0) {
  24963. listeningCamera = this.activeCameras[0];
  24964. }
  24965. else {
  24966. listeningCamera = this.activeCamera;
  24967. }
  24968. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24969. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24970. // for VR cameras
  24971. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24972. listeningCamera = listeningCamera.rigCameras[0];
  24973. }
  24974. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24975. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24976. cameraDirection.normalize();
  24977. // To avoid some errors on GearVR
  24978. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24979. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24980. }
  24981. var i;
  24982. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24983. var sound = this.mainSoundTrack.soundCollection[i];
  24984. if (sound.useCustomAttenuation) {
  24985. sound.updateDistanceFromListener();
  24986. }
  24987. }
  24988. for (i = 0; i < this.soundTracks.length; i++) {
  24989. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24990. sound = this.soundTracks[i].soundCollection[j];
  24991. if (sound.useCustomAttenuation) {
  24992. sound.updateDistanceFromListener();
  24993. }
  24994. }
  24995. }
  24996. }
  24997. };
  24998. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24999. // Audio
  25000. get: function () {
  25001. return this._audioEnabled;
  25002. },
  25003. set: function (value) {
  25004. this._audioEnabled = value;
  25005. if (BABYLON.AudioEngine) {
  25006. if (this._audioEnabled) {
  25007. this._enableAudio();
  25008. }
  25009. else {
  25010. this._disableAudio();
  25011. }
  25012. }
  25013. },
  25014. enumerable: true,
  25015. configurable: true
  25016. });
  25017. Scene.prototype._disableAudio = function () {
  25018. var i;
  25019. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25020. this.mainSoundTrack.soundCollection[i].pause();
  25021. }
  25022. for (i = 0; i < this.soundTracks.length; i++) {
  25023. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25024. this.soundTracks[i].soundCollection[j].pause();
  25025. }
  25026. }
  25027. };
  25028. Scene.prototype._enableAudio = function () {
  25029. var i;
  25030. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25031. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25032. this.mainSoundTrack.soundCollection[i].play();
  25033. }
  25034. }
  25035. for (i = 0; i < this.soundTracks.length; i++) {
  25036. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25037. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25038. this.soundTracks[i].soundCollection[j].play();
  25039. }
  25040. }
  25041. }
  25042. };
  25043. Object.defineProperty(Scene.prototype, "headphone", {
  25044. get: function () {
  25045. return this._headphone;
  25046. },
  25047. set: function (value) {
  25048. this._headphone = value;
  25049. if (BABYLON.AudioEngine) {
  25050. if (this._headphone) {
  25051. this._switchAudioModeForHeadphones();
  25052. }
  25053. else {
  25054. this._switchAudioModeForNormalSpeakers();
  25055. }
  25056. }
  25057. },
  25058. enumerable: true,
  25059. configurable: true
  25060. });
  25061. Scene.prototype._switchAudioModeForHeadphones = function () {
  25062. this.mainSoundTrack.switchPanningModelToHRTF();
  25063. for (var i = 0; i < this.soundTracks.length; i++) {
  25064. this.soundTracks[i].switchPanningModelToHRTF();
  25065. }
  25066. };
  25067. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25068. this.mainSoundTrack.switchPanningModelToEqualPower();
  25069. for (var i = 0; i < this.soundTracks.length; i++) {
  25070. this.soundTracks[i].switchPanningModelToEqualPower();
  25071. }
  25072. };
  25073. /**
  25074. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25075. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25076. * @returns the created depth renderer
  25077. */
  25078. Scene.prototype.enableDepthRenderer = function (camera) {
  25079. camera = camera || this.activeCamera;
  25080. if (!camera) {
  25081. throw "No camera available to enable depth renderer";
  25082. }
  25083. if (!this._depthRenderer[camera.id]) {
  25084. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25085. }
  25086. return this._depthRenderer[camera.id];
  25087. };
  25088. /**
  25089. * Disables a depth renderer for a given camera
  25090. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25091. */
  25092. Scene.prototype.disableDepthRenderer = function (camera) {
  25093. camera = camera || this.activeCamera;
  25094. if (!camera || !this._depthRenderer[camera.id]) {
  25095. return;
  25096. }
  25097. this._depthRenderer[camera.id].dispose();
  25098. delete this._depthRenderer[camera.id];
  25099. };
  25100. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25101. if (ratio === void 0) { ratio = 1; }
  25102. if (this._geometryBufferRenderer) {
  25103. return this._geometryBufferRenderer;
  25104. }
  25105. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25106. if (!this._geometryBufferRenderer.isSupported) {
  25107. this._geometryBufferRenderer = null;
  25108. }
  25109. return this._geometryBufferRenderer;
  25110. };
  25111. Scene.prototype.disableGeometryBufferRenderer = function () {
  25112. if (!this._geometryBufferRenderer) {
  25113. return;
  25114. }
  25115. this._geometryBufferRenderer.dispose();
  25116. this._geometryBufferRenderer = null;
  25117. };
  25118. Scene.prototype.freezeMaterials = function () {
  25119. for (var i = 0; i < this.materials.length; i++) {
  25120. this.materials[i].freeze();
  25121. }
  25122. };
  25123. Scene.prototype.unfreezeMaterials = function () {
  25124. for (var i = 0; i < this.materials.length; i++) {
  25125. this.materials[i].unfreeze();
  25126. }
  25127. };
  25128. Scene.prototype.dispose = function () {
  25129. this.beforeRender = null;
  25130. this.afterRender = null;
  25131. this.skeletons = [];
  25132. this.morphTargetManagers = [];
  25133. this.importedMeshesFiles = new Array();
  25134. this.stopAllAnimations();
  25135. this.resetCachedMaterial();
  25136. for (var key in this._depthRenderer) {
  25137. this._depthRenderer[key].dispose();
  25138. }
  25139. if (this._gamepadManager) {
  25140. this._gamepadManager.dispose();
  25141. this._gamepadManager = null;
  25142. }
  25143. // Smart arrays
  25144. if (this.activeCamera) {
  25145. this.activeCamera._activeMeshes.dispose();
  25146. this.activeCamera = null;
  25147. }
  25148. this._activeMeshes.dispose();
  25149. this._renderingManager.dispose();
  25150. this._processedMaterials.dispose();
  25151. this._activeParticleSystems.dispose();
  25152. this._activeSkeletons.dispose();
  25153. this._softwareSkinnedMeshes.dispose();
  25154. this._renderTargets.dispose();
  25155. this._registeredForLateAnimationBindings.dispose();
  25156. if (this._boundingBoxRenderer) {
  25157. this._boundingBoxRenderer.dispose();
  25158. }
  25159. this._meshesForIntersections.dispose();
  25160. this._toBeDisposed.dispose();
  25161. // Abort active requests
  25162. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25163. var request = _a[_i];
  25164. request.abort();
  25165. }
  25166. // Debug layer
  25167. if (this._debugLayer) {
  25168. this._debugLayer.hide();
  25169. }
  25170. // Events
  25171. this.onDisposeObservable.notifyObservers(this);
  25172. this.onDisposeObservable.clear();
  25173. this.onBeforeRenderObservable.clear();
  25174. this.onAfterRenderObservable.clear();
  25175. this.OnBeforeRenderTargetsRenderObservable.clear();
  25176. this.OnAfterRenderTargetsRenderObservable.clear();
  25177. this.onAfterStepObservable.clear();
  25178. this.onBeforeStepObservable.clear();
  25179. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25180. this.onAfterActiveMeshesEvaluationObservable.clear();
  25181. this.onBeforeParticlesRenderingObservable.clear();
  25182. this.onAfterParticlesRenderingObservable.clear();
  25183. this.onBeforeSpritesRenderingObservable.clear();
  25184. this.onAfterSpritesRenderingObservable.clear();
  25185. this.onBeforeDrawPhaseObservable.clear();
  25186. this.onAfterDrawPhaseObservable.clear();
  25187. this.onBeforePhysicsObservable.clear();
  25188. this.onAfterPhysicsObservable.clear();
  25189. this.onBeforeAnimationsObservable.clear();
  25190. this.onAfterAnimationsObservable.clear();
  25191. this.onDataLoadedObservable.clear();
  25192. this.detachControl();
  25193. // Release sounds & sounds tracks
  25194. if (BABYLON.AudioEngine) {
  25195. this.disposeSounds();
  25196. }
  25197. // VR Helper
  25198. if (this.VRHelper) {
  25199. this.VRHelper.dispose();
  25200. }
  25201. // Detach cameras
  25202. var canvas = this._engine.getRenderingCanvas();
  25203. if (canvas) {
  25204. var index;
  25205. for (index = 0; index < this.cameras.length; index++) {
  25206. this.cameras[index].detachControl(canvas);
  25207. }
  25208. }
  25209. // Release animation groups
  25210. while (this.animationGroups.length) {
  25211. this.animationGroups[0].dispose();
  25212. }
  25213. // Release lights
  25214. while (this.lights.length) {
  25215. this.lights[0].dispose();
  25216. }
  25217. // Release meshes
  25218. while (this.meshes.length) {
  25219. this.meshes[0].dispose(true);
  25220. }
  25221. while (this.transformNodes.length) {
  25222. this.removeTransformNode(this.transformNodes[0]);
  25223. }
  25224. // Release cameras
  25225. while (this.cameras.length) {
  25226. this.cameras[0].dispose();
  25227. }
  25228. // Release materials
  25229. if (this.defaultMaterial) {
  25230. this.defaultMaterial.dispose();
  25231. }
  25232. while (this.multiMaterials.length) {
  25233. this.multiMaterials[0].dispose();
  25234. }
  25235. while (this.materials.length) {
  25236. this.materials[0].dispose();
  25237. }
  25238. // Release particles
  25239. while (this.particleSystems.length) {
  25240. this.particleSystems[0].dispose();
  25241. }
  25242. // Release sprites
  25243. while (this.spriteManagers.length) {
  25244. this.spriteManagers[0].dispose();
  25245. }
  25246. // Release postProcesses
  25247. while (this.postProcesses.length) {
  25248. this.postProcesses[0].dispose();
  25249. }
  25250. // Release layers
  25251. while (this.layers.length) {
  25252. this.layers[0].dispose();
  25253. }
  25254. while (this.effectLayers.length) {
  25255. this.effectLayers[0].dispose();
  25256. }
  25257. // Release textures
  25258. while (this.textures.length) {
  25259. this.textures[0].dispose();
  25260. }
  25261. // Release UBO
  25262. this._sceneUbo.dispose();
  25263. if (this._alternateSceneUbo) {
  25264. this._alternateSceneUbo.dispose();
  25265. }
  25266. // Post-processes
  25267. this.postProcessManager.dispose();
  25268. if (this._postProcessRenderPipelineManager) {
  25269. this._postProcessRenderPipelineManager.dispose();
  25270. }
  25271. // Physics
  25272. if (this._physicsEngine) {
  25273. this.disablePhysicsEngine();
  25274. }
  25275. // Remove from engine
  25276. index = this._engine.scenes.indexOf(this);
  25277. if (index > -1) {
  25278. this._engine.scenes.splice(index, 1);
  25279. }
  25280. this._engine.wipeCaches(true);
  25281. this._isDisposed = true;
  25282. };
  25283. Object.defineProperty(Scene.prototype, "isDisposed", {
  25284. get: function () {
  25285. return this._isDisposed;
  25286. },
  25287. enumerable: true,
  25288. configurable: true
  25289. });
  25290. // Release sounds & sounds tracks
  25291. Scene.prototype.disposeSounds = function () {
  25292. if (!this._mainSoundTrack) {
  25293. return;
  25294. }
  25295. this.mainSoundTrack.dispose();
  25296. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25297. this.soundTracks[scIndex].dispose();
  25298. }
  25299. };
  25300. // Octrees
  25301. /**
  25302. * Get the world extend vectors with an optional filter
  25303. *
  25304. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25305. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25306. */
  25307. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25308. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25309. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25310. filterPredicate = filterPredicate || (function () { return true; });
  25311. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25312. mesh.computeWorldMatrix(true);
  25313. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25314. return;
  25315. }
  25316. var boundingInfo = mesh.getBoundingInfo();
  25317. var minBox = boundingInfo.boundingBox.minimumWorld;
  25318. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25319. BABYLON.Tools.CheckExtends(minBox, min, max);
  25320. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25321. });
  25322. return {
  25323. min: min,
  25324. max: max
  25325. };
  25326. };
  25327. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25328. if (maxCapacity === void 0) { maxCapacity = 64; }
  25329. if (maxDepth === void 0) { maxDepth = 2; }
  25330. if (!this._selectionOctree) {
  25331. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25332. }
  25333. var worldExtends = this.getWorldExtends();
  25334. // Update octree
  25335. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25336. return this._selectionOctree;
  25337. };
  25338. // Picking
  25339. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25340. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25341. var result = BABYLON.Ray.Zero();
  25342. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25343. return result;
  25344. };
  25345. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25346. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25347. var engine = this._engine;
  25348. if (!camera) {
  25349. if (!this.activeCamera)
  25350. throw new Error("Active camera not set");
  25351. camera = this.activeCamera;
  25352. }
  25353. var cameraViewport = camera.viewport;
  25354. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25355. // Moving coordinates to local viewport world
  25356. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25357. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25358. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25359. return this;
  25360. };
  25361. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25362. var result = BABYLON.Ray.Zero();
  25363. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25364. return result;
  25365. };
  25366. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25367. if (!BABYLON.PickingInfo) {
  25368. return this;
  25369. }
  25370. var engine = this._engine;
  25371. if (!camera) {
  25372. if (!this.activeCamera)
  25373. throw new Error("Active camera not set");
  25374. camera = this.activeCamera;
  25375. }
  25376. var cameraViewport = camera.viewport;
  25377. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25378. var identity = BABYLON.Matrix.Identity();
  25379. // Moving coordinates to local viewport world
  25380. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25381. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25382. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25383. return this;
  25384. };
  25385. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25386. if (!BABYLON.PickingInfo) {
  25387. return null;
  25388. }
  25389. var pickingInfo = null;
  25390. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25391. var mesh = this.meshes[meshIndex];
  25392. if (predicate) {
  25393. if (!predicate(mesh)) {
  25394. continue;
  25395. }
  25396. }
  25397. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25398. continue;
  25399. }
  25400. var world = mesh.getWorldMatrix();
  25401. var ray = rayFunction(world);
  25402. var result = mesh.intersects(ray, fastCheck);
  25403. if (!result || !result.hit)
  25404. continue;
  25405. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25406. continue;
  25407. pickingInfo = result;
  25408. if (fastCheck) {
  25409. break;
  25410. }
  25411. }
  25412. return pickingInfo || new BABYLON.PickingInfo();
  25413. };
  25414. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25415. if (!BABYLON.PickingInfo) {
  25416. return null;
  25417. }
  25418. var pickingInfos = new Array();
  25419. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25420. var mesh = this.meshes[meshIndex];
  25421. if (predicate) {
  25422. if (!predicate(mesh)) {
  25423. continue;
  25424. }
  25425. }
  25426. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25427. continue;
  25428. }
  25429. var world = mesh.getWorldMatrix();
  25430. var ray = rayFunction(world);
  25431. var result = mesh.intersects(ray, false);
  25432. if (!result || !result.hit)
  25433. continue;
  25434. pickingInfos.push(result);
  25435. }
  25436. return pickingInfos;
  25437. };
  25438. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25439. if (!BABYLON.PickingInfo) {
  25440. return null;
  25441. }
  25442. var pickingInfo = null;
  25443. if (!camera) {
  25444. if (!this.activeCamera) {
  25445. return null;
  25446. }
  25447. camera = this.activeCamera;
  25448. }
  25449. if (this.spriteManagers.length > 0) {
  25450. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25451. var spriteManager = this.spriteManagers[spriteIndex];
  25452. if (!spriteManager.isPickable) {
  25453. continue;
  25454. }
  25455. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25456. if (!result || !result.hit)
  25457. continue;
  25458. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25459. continue;
  25460. pickingInfo = result;
  25461. if (fastCheck) {
  25462. break;
  25463. }
  25464. }
  25465. }
  25466. return pickingInfo || new BABYLON.PickingInfo();
  25467. };
  25468. /** Launch a ray to try to pick a mesh in the scene
  25469. * @param x position on screen
  25470. * @param y position on screen
  25471. * @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
  25472. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25473. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25474. */
  25475. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25476. var _this = this;
  25477. if (!BABYLON.PickingInfo) {
  25478. return null;
  25479. }
  25480. return this._internalPick(function (world) {
  25481. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25482. return _this._tempPickingRay;
  25483. }, predicate, fastCheck);
  25484. };
  25485. /** Launch a ray to try to pick a sprite in the scene
  25486. * @param x position on screen
  25487. * @param y position on screen
  25488. * @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
  25489. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25490. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25491. */
  25492. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25493. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25494. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25495. };
  25496. /** Use the given ray to pick a mesh in the scene
  25497. * @param ray The ray to use to pick meshes
  25498. * @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
  25499. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25500. */
  25501. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25502. var _this = this;
  25503. return this._internalPick(function (world) {
  25504. if (!_this._pickWithRayInverseMatrix) {
  25505. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25506. }
  25507. world.invertToRef(_this._pickWithRayInverseMatrix);
  25508. if (!_this._cachedRayForTransform) {
  25509. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25510. }
  25511. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25512. return _this._cachedRayForTransform;
  25513. }, predicate, fastCheck);
  25514. };
  25515. /**
  25516. * Launch a ray to try to pick a mesh in the scene
  25517. * @param x X position on screen
  25518. * @param y Y position on screen
  25519. * @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
  25520. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25521. */
  25522. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25523. var _this = this;
  25524. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25525. };
  25526. /**
  25527. * Launch a ray to try to pick a mesh in the scene
  25528. * @param ray Ray to use
  25529. * @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
  25530. */
  25531. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25532. var _this = this;
  25533. return this._internalMultiPick(function (world) {
  25534. if (!_this._pickWithRayInverseMatrix) {
  25535. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25536. }
  25537. world.invertToRef(_this._pickWithRayInverseMatrix);
  25538. if (!_this._cachedRayForTransform) {
  25539. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25540. }
  25541. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25542. return _this._cachedRayForTransform;
  25543. }, predicate);
  25544. };
  25545. Scene.prototype.setPointerOverMesh = function (mesh) {
  25546. if (this._pointerOverMesh === mesh) {
  25547. return;
  25548. }
  25549. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25550. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25551. }
  25552. this._pointerOverMesh = mesh;
  25553. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25554. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25555. }
  25556. };
  25557. Scene.prototype.getPointerOverMesh = function () {
  25558. return this._pointerOverMesh;
  25559. };
  25560. Scene.prototype.setPointerOverSprite = function (sprite) {
  25561. if (this._pointerOverSprite === sprite) {
  25562. return;
  25563. }
  25564. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25565. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25566. }
  25567. this._pointerOverSprite = sprite;
  25568. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25569. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25570. }
  25571. };
  25572. Scene.prototype.getPointerOverSprite = function () {
  25573. return this._pointerOverSprite;
  25574. };
  25575. // Physics
  25576. Scene.prototype.getPhysicsEngine = function () {
  25577. return this._physicsEngine;
  25578. };
  25579. /**
  25580. * Enables physics to the current scene
  25581. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25582. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25583. * @return {boolean} was the physics engine initialized
  25584. */
  25585. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25586. if (gravity === void 0) { gravity = null; }
  25587. if (this._physicsEngine) {
  25588. return true;
  25589. }
  25590. try {
  25591. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25592. return true;
  25593. }
  25594. catch (e) {
  25595. BABYLON.Tools.Error(e.message);
  25596. return false;
  25597. }
  25598. };
  25599. Scene.prototype.disablePhysicsEngine = function () {
  25600. if (!this._physicsEngine) {
  25601. return;
  25602. }
  25603. this._physicsEngine.dispose();
  25604. this._physicsEngine = null;
  25605. };
  25606. Scene.prototype.isPhysicsEnabled = function () {
  25607. return this._physicsEngine !== undefined;
  25608. };
  25609. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25610. var mesh = compound.parts[0].mesh;
  25611. if (mesh.physicsImpostor) {
  25612. mesh.physicsImpostor.dispose();
  25613. mesh.physicsImpostor = null;
  25614. }
  25615. };
  25616. // Misc.
  25617. Scene.prototype._rebuildGeometries = function () {
  25618. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25619. var geometry = _a[_i];
  25620. geometry._rebuild();
  25621. }
  25622. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25623. var mesh = _c[_b];
  25624. mesh._rebuild();
  25625. }
  25626. if (this.postProcessManager) {
  25627. this.postProcessManager._rebuild();
  25628. }
  25629. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25630. var layer = _e[_d];
  25631. layer._rebuild();
  25632. }
  25633. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25634. var effectLayer = _g[_f];
  25635. effectLayer._rebuild();
  25636. }
  25637. if (this._boundingBoxRenderer) {
  25638. this._boundingBoxRenderer._rebuild();
  25639. }
  25640. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25641. var system = _j[_h];
  25642. system.rebuild();
  25643. }
  25644. if (this._postProcessRenderPipelineManager) {
  25645. this._postProcessRenderPipelineManager._rebuild();
  25646. }
  25647. };
  25648. Scene.prototype._rebuildTextures = function () {
  25649. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25650. var texture = _a[_i];
  25651. texture._rebuild();
  25652. }
  25653. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25654. };
  25655. /**
  25656. * Creates a default light for the scene.
  25657. * @param replace Whether to replace the existing lights in the scene.
  25658. */
  25659. Scene.prototype.createDefaultLight = function (replace) {
  25660. if (replace === void 0) { replace = false; }
  25661. // Dispose existing light in replace mode.
  25662. if (replace) {
  25663. if (this.lights) {
  25664. for (var i = 0; i < this.lights.length; i++) {
  25665. this.lights[i].dispose();
  25666. }
  25667. }
  25668. }
  25669. // Light
  25670. if (this.lights.length === 0) {
  25671. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25672. }
  25673. };
  25674. /**
  25675. * Creates a default camera for the scene.
  25676. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25677. * @param replace Whether to replace the existing active camera in the scene.
  25678. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25679. */
  25680. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25681. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25682. if (replace === void 0) { replace = false; }
  25683. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25684. // Dispose existing camera in replace mode.
  25685. if (replace) {
  25686. if (this.activeCamera) {
  25687. this.activeCamera.dispose();
  25688. this.activeCamera = null;
  25689. }
  25690. }
  25691. // Camera
  25692. if (!this.activeCamera) {
  25693. var worldExtends = this.getWorldExtends();
  25694. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25695. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25696. var camera;
  25697. var radius = worldSize.length() * 1.5;
  25698. // empty scene scenario!
  25699. if (!isFinite(radius)) {
  25700. radius = 1;
  25701. worldCenter.copyFromFloats(0, 0, 0);
  25702. }
  25703. if (createArcRotateCamera) {
  25704. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25705. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25706. arcRotateCamera.wheelPrecision = 100 / radius;
  25707. camera = arcRotateCamera;
  25708. }
  25709. else {
  25710. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25711. freeCamera.setTarget(worldCenter);
  25712. camera = freeCamera;
  25713. }
  25714. camera.minZ = radius * 0.01;
  25715. camera.maxZ = radius * 1000;
  25716. camera.speed = radius * 0.2;
  25717. this.activeCamera = camera;
  25718. var canvas = this.getEngine().getRenderingCanvas();
  25719. if (attachCameraControls && canvas) {
  25720. camera.attachControl(canvas);
  25721. }
  25722. }
  25723. };
  25724. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25725. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25726. if (replace === void 0) { replace = false; }
  25727. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25728. this.createDefaultLight(replace);
  25729. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25730. };
  25731. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25732. if (pbr === void 0) { pbr = false; }
  25733. if (scale === void 0) { scale = 1000; }
  25734. if (blur === void 0) { blur = 0; }
  25735. if (environmentTexture) {
  25736. this.environmentTexture = environmentTexture;
  25737. }
  25738. if (!this.environmentTexture) {
  25739. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25740. return null;
  25741. }
  25742. // Skybox
  25743. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25744. if (pbr) {
  25745. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25746. hdrSkyboxMaterial.backFaceCulling = false;
  25747. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25748. if (hdrSkyboxMaterial.reflectionTexture) {
  25749. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25750. }
  25751. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25752. hdrSkyboxMaterial.disableLighting = true;
  25753. hdrSkyboxMaterial.twoSidedLighting = true;
  25754. hdrSkybox.infiniteDistance = true;
  25755. hdrSkybox.material = hdrSkyboxMaterial;
  25756. }
  25757. else {
  25758. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25759. skyboxMaterial.backFaceCulling = false;
  25760. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25761. if (skyboxMaterial.reflectionTexture) {
  25762. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25763. }
  25764. skyboxMaterial.disableLighting = true;
  25765. hdrSkybox.infiniteDistance = true;
  25766. hdrSkybox.material = skyboxMaterial;
  25767. }
  25768. return hdrSkybox;
  25769. };
  25770. Scene.prototype.createDefaultEnvironment = function (options) {
  25771. if (BABYLON.EnvironmentHelper) {
  25772. return new BABYLON.EnvironmentHelper(options, this);
  25773. }
  25774. return null;
  25775. };
  25776. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25777. if (webVROptions === void 0) { webVROptions = {}; }
  25778. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25779. };
  25780. // Tags
  25781. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25782. if (tagsQuery === undefined) {
  25783. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25784. return list;
  25785. }
  25786. var listByTags = [];
  25787. forEach = forEach || (function (item) { return; });
  25788. for (var i in list) {
  25789. var item = list[i];
  25790. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25791. listByTags.push(item);
  25792. forEach(item);
  25793. }
  25794. }
  25795. return listByTags;
  25796. };
  25797. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25798. return this._getByTags(this.meshes, tagsQuery, forEach);
  25799. };
  25800. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25801. return this._getByTags(this.cameras, tagsQuery, forEach);
  25802. };
  25803. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25804. return this._getByTags(this.lights, tagsQuery, forEach);
  25805. };
  25806. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25807. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25808. };
  25809. /**
  25810. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25811. * This allowed control for front to back rendering or reversly depending of the special needs.
  25812. *
  25813. * @param renderingGroupId The rendering group id corresponding to its index
  25814. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25815. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25816. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25817. */
  25818. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25819. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25820. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25821. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25822. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25823. };
  25824. /**
  25825. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25826. *
  25827. * @param renderingGroupId The rendering group id corresponding to its index
  25828. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25829. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25830. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25831. */
  25832. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25833. if (depth === void 0) { depth = true; }
  25834. if (stencil === void 0) { stencil = true; }
  25835. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25836. };
  25837. /**
  25838. * Will flag all materials as dirty to trigger new shader compilation
  25839. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25840. */
  25841. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25842. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25843. var material = _a[_i];
  25844. if (predicate && !predicate(material)) {
  25845. continue;
  25846. }
  25847. material.markAsDirty(flag);
  25848. }
  25849. };
  25850. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25851. var _this = this;
  25852. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25853. this._activeRequests.push(request);
  25854. request.onCompleteObservable.add(function (request) {
  25855. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25856. });
  25857. return request;
  25858. };
  25859. /** @ignore */
  25860. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25861. var _this = this;
  25862. return new Promise(function (resolve, reject) {
  25863. _this._loadFile(url, function (data) {
  25864. resolve(data);
  25865. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25866. reject(exception);
  25867. });
  25868. });
  25869. };
  25870. // Statics
  25871. Scene._FOGMODE_NONE = 0;
  25872. Scene._FOGMODE_EXP = 1;
  25873. Scene._FOGMODE_EXP2 = 2;
  25874. Scene._FOGMODE_LINEAR = 3;
  25875. Scene._uniqueIdCounter = 0;
  25876. Scene.MinDeltaTime = 1.0;
  25877. Scene.MaxDeltaTime = 1000.0;
  25878. /** The distance in pixel that you have to move to prevent some events */
  25879. Scene.DragMovementThreshold = 10; // in pixels
  25880. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25881. Scene.LongPressDelay = 500; // in milliseconds
  25882. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25883. Scene.DoubleClickDelay = 300; // in milliseconds
  25884. /** If you need to check double click without raising a single click at first click, enable this flag */
  25885. Scene.ExclusiveDoubleClickMode = false;
  25886. return Scene;
  25887. }());
  25888. BABYLON.Scene = Scene;
  25889. })(BABYLON || (BABYLON = {}));
  25890. //# sourceMappingURL=babylon.scene.js.map
  25891. "use strict";
  25892. var BABYLON;
  25893. (function (BABYLON) {
  25894. /**
  25895. * Set of assets to keep when moving a scene into an asset container.
  25896. */
  25897. var KeepAssets = /** @class */ (function () {
  25898. function KeepAssets() {
  25899. /**
  25900. * Cameras to keep.
  25901. */
  25902. this.cameras = new Array();
  25903. /**
  25904. * Lights to keep.
  25905. */
  25906. this.lights = new Array();
  25907. /**
  25908. * Meshes to keep.
  25909. */
  25910. this.meshes = new Array();
  25911. /**
  25912. * Skeletons to keep.
  25913. */
  25914. this.skeletons = new Array();
  25915. /**
  25916. * ParticleSystems to keep.
  25917. */
  25918. this.particleSystems = new Array();
  25919. /**
  25920. * Animations to keep.
  25921. */
  25922. this.animations = new Array();
  25923. /**
  25924. * MultiMaterials to keep.
  25925. */
  25926. this.multiMaterials = new Array();
  25927. /**
  25928. * Materials to keep.
  25929. */
  25930. this.materials = new Array();
  25931. /**
  25932. * MorphTargetManagers to keep.
  25933. */
  25934. this.morphTargetManagers = new Array();
  25935. /**
  25936. * Geometries to keep.
  25937. */
  25938. this.geometries = new Array();
  25939. /**
  25940. * TransformNodes to keep.
  25941. */
  25942. this.transformNodes = new Array();
  25943. /**
  25944. * LensFlareSystems to keep.
  25945. */
  25946. this.lensFlareSystems = new Array();
  25947. /**
  25948. * ShadowGenerators to keep.
  25949. */
  25950. this.shadowGenerators = new Array();
  25951. /**
  25952. * ActionManagers to keep.
  25953. */
  25954. this.actionManagers = new Array();
  25955. /**
  25956. * Sounds to keep.
  25957. */
  25958. this.sounds = new Array();
  25959. }
  25960. return KeepAssets;
  25961. }());
  25962. BABYLON.KeepAssets = KeepAssets;
  25963. /**
  25964. * Container with a set of assets that can be added or removed from a scene.
  25965. */
  25966. var AssetContainer = /** @class */ (function () {
  25967. /**
  25968. * Instantiates an AssetContainer.
  25969. * @param scene The scene the AssetContainer belongs to.
  25970. */
  25971. function AssetContainer(scene) {
  25972. // Objects
  25973. /**
  25974. * Cameras populated in the container.
  25975. */
  25976. this.cameras = new Array();
  25977. /**
  25978. * Lights populated in the container.
  25979. */
  25980. this.lights = new Array();
  25981. /**
  25982. * Meshes populated in the container.
  25983. */
  25984. this.meshes = new Array();
  25985. /**
  25986. * Skeletons populated in the container.
  25987. */
  25988. this.skeletons = new Array();
  25989. /**
  25990. * ParticleSystems populated in the container.
  25991. */
  25992. this.particleSystems = new Array();
  25993. /**
  25994. * Animations populated in the container.
  25995. */
  25996. this.animations = new Array();
  25997. /**
  25998. * MultiMaterials populated in the container.
  25999. */
  26000. this.multiMaterials = new Array();
  26001. /**
  26002. * Materials populated in the container.
  26003. */
  26004. this.materials = new Array();
  26005. /**
  26006. * MorphTargetManagers populated in the container.
  26007. */
  26008. this.morphTargetManagers = new Array();
  26009. /**
  26010. * Geometries populated in the container.
  26011. */
  26012. this.geometries = new Array();
  26013. /**
  26014. * TransformNodes populated in the container.
  26015. */
  26016. this.transformNodes = new Array();
  26017. /**
  26018. * LensFlareSystems populated in the container.
  26019. */
  26020. this.lensFlareSystems = new Array();
  26021. /**
  26022. * ShadowGenerators populated in the container.
  26023. */
  26024. this.shadowGenerators = new Array();
  26025. /**
  26026. * ActionManagers populated in the container.
  26027. */
  26028. this.actionManagers = new Array();
  26029. /**
  26030. * Sounds populated in the container.
  26031. */
  26032. this.sounds = new Array();
  26033. this.scene = scene;
  26034. }
  26035. /**
  26036. * Adds all the assets from the container to the scene.
  26037. */
  26038. AssetContainer.prototype.addAllToScene = function () {
  26039. var _this = this;
  26040. this.cameras.forEach(function (o) {
  26041. _this.scene.addCamera(o);
  26042. });
  26043. this.lights.forEach(function (o) {
  26044. _this.scene.addLight(o);
  26045. });
  26046. this.meshes.forEach(function (o) {
  26047. _this.scene.addMesh(o);
  26048. });
  26049. this.skeletons.forEach(function (o) {
  26050. _this.scene.addSkeleton(o);
  26051. });
  26052. this.particleSystems.forEach(function (o) {
  26053. _this.scene.addParticleSystem(o);
  26054. });
  26055. this.animations.forEach(function (o) {
  26056. _this.scene.addAnimation(o);
  26057. });
  26058. this.multiMaterials.forEach(function (o) {
  26059. _this.scene.addMultiMaterial(o);
  26060. });
  26061. this.materials.forEach(function (o) {
  26062. _this.scene.addMaterial(o);
  26063. });
  26064. this.morphTargetManagers.forEach(function (o) {
  26065. _this.scene.addMorphTargetManager(o);
  26066. });
  26067. this.geometries.forEach(function (o) {
  26068. _this.scene.addGeometry(o);
  26069. });
  26070. this.transformNodes.forEach(function (o) {
  26071. _this.scene.addTransformNode(o);
  26072. });
  26073. this.lensFlareSystems.forEach(function (o) {
  26074. _this.scene.addLensFlareSystem(o);
  26075. });
  26076. this.actionManagers.forEach(function (o) {
  26077. _this.scene.addActionManager(o);
  26078. });
  26079. this.sounds.forEach(function (o) {
  26080. o.play();
  26081. o.autoplay = true;
  26082. _this.scene.mainSoundTrack.AddSound(o);
  26083. });
  26084. };
  26085. /**
  26086. * Removes all the assets in the container from the scene
  26087. */
  26088. AssetContainer.prototype.removeAllFromScene = function () {
  26089. var _this = this;
  26090. this.cameras.forEach(function (o) {
  26091. _this.scene.removeCamera(o);
  26092. });
  26093. this.lights.forEach(function (o) {
  26094. _this.scene.removeLight(o);
  26095. });
  26096. this.meshes.forEach(function (o) {
  26097. _this.scene.removeMesh(o);
  26098. });
  26099. this.skeletons.forEach(function (o) {
  26100. _this.scene.removeSkeleton(o);
  26101. });
  26102. this.particleSystems.forEach(function (o) {
  26103. _this.scene.removeParticleSystem(o);
  26104. });
  26105. this.animations.forEach(function (o) {
  26106. _this.scene.removeAnimation(o);
  26107. });
  26108. this.multiMaterials.forEach(function (o) {
  26109. _this.scene.removeMultiMaterial(o);
  26110. });
  26111. this.materials.forEach(function (o) {
  26112. _this.scene.removeMaterial(o);
  26113. });
  26114. this.morphTargetManagers.forEach(function (o) {
  26115. _this.scene.removeMorphTargetManager(o);
  26116. });
  26117. this.geometries.forEach(function (o) {
  26118. _this.scene.removeGeometry(o);
  26119. });
  26120. this.transformNodes.forEach(function (o) {
  26121. _this.scene.removeTransformNode(o);
  26122. });
  26123. this.lensFlareSystems.forEach(function (o) {
  26124. _this.scene.removeLensFlareSystem(o);
  26125. });
  26126. this.actionManagers.forEach(function (o) {
  26127. _this.scene.removeActionManager(o);
  26128. });
  26129. this.sounds.forEach(function (o) {
  26130. o.stop();
  26131. o.autoplay = false;
  26132. _this.scene.mainSoundTrack.RemoveSound(o);
  26133. });
  26134. };
  26135. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26136. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26137. var asset = sourceAssets_1[_i];
  26138. var move = true;
  26139. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26140. var keepAsset = keepAssets_1[_a];
  26141. if (asset === keepAsset) {
  26142. move = false;
  26143. break;
  26144. }
  26145. }
  26146. if (move) {
  26147. targetAssets.push(asset);
  26148. }
  26149. }
  26150. };
  26151. /**
  26152. * Removes all the assets contained in the scene and adds them to the container.
  26153. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26154. */
  26155. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26156. if (keepAssets === undefined) {
  26157. keepAssets = new KeepAssets();
  26158. }
  26159. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26160. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26161. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26162. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26163. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26164. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26165. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26166. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26167. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26168. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26169. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26170. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26171. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26172. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26173. this.removeAllFromScene();
  26174. };
  26175. return AssetContainer;
  26176. }());
  26177. BABYLON.AssetContainer = AssetContainer;
  26178. })(BABYLON || (BABYLON = {}));
  26179. //# sourceMappingURL=babylon.assetContainer.js.map
  26180. "use strict";
  26181. var BABYLON;
  26182. (function (BABYLON) {
  26183. var Buffer = /** @class */ (function () {
  26184. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26185. if (instanced === void 0) { instanced = false; }
  26186. if (engine instanceof BABYLON.Mesh) {
  26187. this._engine = engine.getScene().getEngine();
  26188. }
  26189. else {
  26190. this._engine = engine;
  26191. }
  26192. this._updatable = updatable;
  26193. this._instanced = instanced;
  26194. this._data = data;
  26195. this._strideSize = stride;
  26196. if (!postponeInternalCreation) {
  26197. this.create();
  26198. }
  26199. }
  26200. /**
  26201. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26202. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26203. * @param offset defines offset in the buffer (0 by default)
  26204. * @param size defines the size in floats of attributes (position is 3 for instance)
  26205. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26206. * @param instanced defines if the vertex buffer contains indexed data
  26207. * @returns the new vertex buffer
  26208. */
  26209. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26210. // a lot of these parameters are ignored as they are overriden by the buffer
  26211. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26212. };
  26213. // Properties
  26214. Buffer.prototype.isUpdatable = function () {
  26215. return this._updatable;
  26216. };
  26217. Buffer.prototype.getData = function () {
  26218. return this._data;
  26219. };
  26220. Buffer.prototype.getBuffer = function () {
  26221. return this._buffer;
  26222. };
  26223. Buffer.prototype.getStrideSize = function () {
  26224. return this._strideSize;
  26225. };
  26226. // public getIsInstanced(): boolean {
  26227. // return this._instanced;
  26228. // }
  26229. // public get instanceDivisor(): number {
  26230. // return this._instanceDivisor;
  26231. // }
  26232. // public set instanceDivisor(value: number) {
  26233. // this._instanceDivisor = value;
  26234. // if (value == 0) {
  26235. // this._instanced = false;
  26236. // } else {
  26237. // this._instanced = true;
  26238. // }
  26239. // }
  26240. // Methods
  26241. Buffer.prototype.create = function (data) {
  26242. if (data === void 0) { data = null; }
  26243. if (!data && this._buffer) {
  26244. return; // nothing to do
  26245. }
  26246. data = data || this._data;
  26247. if (!data) {
  26248. return;
  26249. }
  26250. if (!this._buffer) {
  26251. if (this._updatable) {
  26252. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26253. this._data = data;
  26254. }
  26255. else {
  26256. this._buffer = this._engine.createVertexBuffer(data);
  26257. }
  26258. }
  26259. else if (this._updatable) {
  26260. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26261. this._data = data;
  26262. }
  26263. };
  26264. Buffer.prototype._rebuild = function () {
  26265. this._buffer = null;
  26266. this.create(this._data);
  26267. };
  26268. Buffer.prototype.update = function (data) {
  26269. this.create(data);
  26270. };
  26271. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26272. if (!this._buffer) {
  26273. return;
  26274. }
  26275. if (this._updatable) {
  26276. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26277. this._data = null;
  26278. }
  26279. };
  26280. Buffer.prototype.dispose = function () {
  26281. if (!this._buffer) {
  26282. return;
  26283. }
  26284. if (this._engine._releaseBuffer(this._buffer)) {
  26285. this._buffer = null;
  26286. }
  26287. };
  26288. return Buffer;
  26289. }());
  26290. BABYLON.Buffer = Buffer;
  26291. })(BABYLON || (BABYLON = {}));
  26292. //# sourceMappingURL=babylon.buffer.js.map
  26293. "use strict";
  26294. var BABYLON;
  26295. (function (BABYLON) {
  26296. var VertexBuffer = /** @class */ (function () {
  26297. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26298. if (data instanceof BABYLON.Buffer) {
  26299. if (!stride) {
  26300. stride = data.getStrideSize();
  26301. }
  26302. this._buffer = data;
  26303. this._ownsBuffer = false;
  26304. }
  26305. else {
  26306. if (!stride) {
  26307. stride = VertexBuffer.DeduceStride(kind);
  26308. }
  26309. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26310. this._ownsBuffer = true;
  26311. }
  26312. this._stride = stride;
  26313. this._instanced = instanced !== undefined ? instanced : false;
  26314. this._instanceDivisor = instanced ? 1 : 0;
  26315. this._offset = offset ? offset : 0;
  26316. this._size = size ? size : stride;
  26317. this._kind = kind;
  26318. }
  26319. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26320. /**
  26321. * Gets or sets the instance divisor when in instanced mode
  26322. */
  26323. get: function () {
  26324. return this._instanceDivisor;
  26325. },
  26326. set: function (value) {
  26327. this._instanceDivisor = value;
  26328. if (value == 0) {
  26329. this._instanced = false;
  26330. }
  26331. else {
  26332. this._instanced = true;
  26333. }
  26334. },
  26335. enumerable: true,
  26336. configurable: true
  26337. });
  26338. VertexBuffer.prototype._rebuild = function () {
  26339. if (!this._buffer) {
  26340. return;
  26341. }
  26342. this._buffer._rebuild();
  26343. };
  26344. /**
  26345. * Returns the kind of the VertexBuffer (string).
  26346. */
  26347. VertexBuffer.prototype.getKind = function () {
  26348. return this._kind;
  26349. };
  26350. // Properties
  26351. /**
  26352. * Boolean : is the VertexBuffer updatable ?
  26353. */
  26354. VertexBuffer.prototype.isUpdatable = function () {
  26355. return this._buffer.isUpdatable();
  26356. };
  26357. /**
  26358. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26359. */
  26360. VertexBuffer.prototype.getData = function () {
  26361. return this._buffer.getData();
  26362. };
  26363. /**
  26364. * Returns the WebGLBuffer associated to the VertexBuffer.
  26365. */
  26366. VertexBuffer.prototype.getBuffer = function () {
  26367. return this._buffer.getBuffer();
  26368. };
  26369. /**
  26370. * Returns the stride of the VertexBuffer (integer).
  26371. */
  26372. VertexBuffer.prototype.getStrideSize = function () {
  26373. return this._stride;
  26374. };
  26375. /**
  26376. * Returns the offset (integer).
  26377. */
  26378. VertexBuffer.prototype.getOffset = function () {
  26379. return this._offset;
  26380. };
  26381. /**
  26382. * Returns the VertexBuffer total size (integer).
  26383. */
  26384. VertexBuffer.prototype.getSize = function () {
  26385. return this._size;
  26386. };
  26387. /**
  26388. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26389. */
  26390. VertexBuffer.prototype.getIsInstanced = function () {
  26391. return this._instanced;
  26392. };
  26393. /**
  26394. * Returns the instancing divisor, zero for non-instanced (integer).
  26395. */
  26396. VertexBuffer.prototype.getInstanceDivisor = function () {
  26397. return this._instanceDivisor;
  26398. };
  26399. // Methods
  26400. /**
  26401. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26402. * Returns the created WebGLBuffer.
  26403. */
  26404. VertexBuffer.prototype.create = function (data) {
  26405. return this._buffer.create(data);
  26406. };
  26407. /**
  26408. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26409. * This function will create a new buffer if the current one is not updatable
  26410. * Returns the updated WebGLBuffer.
  26411. */
  26412. VertexBuffer.prototype.update = function (data) {
  26413. return this._buffer.update(data);
  26414. };
  26415. /**
  26416. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26417. * Returns the directly updated WebGLBuffer.
  26418. */
  26419. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26420. return this._buffer.updateDirectly(data, offset);
  26421. };
  26422. /**
  26423. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26424. */
  26425. VertexBuffer.prototype.dispose = function () {
  26426. if (this._ownsBuffer) {
  26427. this._buffer.dispose();
  26428. }
  26429. };
  26430. Object.defineProperty(VertexBuffer, "PositionKind", {
  26431. get: function () {
  26432. return VertexBuffer._PositionKind;
  26433. },
  26434. enumerable: true,
  26435. configurable: true
  26436. });
  26437. Object.defineProperty(VertexBuffer, "NormalKind", {
  26438. get: function () {
  26439. return VertexBuffer._NormalKind;
  26440. },
  26441. enumerable: true,
  26442. configurable: true
  26443. });
  26444. Object.defineProperty(VertexBuffer, "TangentKind", {
  26445. get: function () {
  26446. return VertexBuffer._TangentKind;
  26447. },
  26448. enumerable: true,
  26449. configurable: true
  26450. });
  26451. Object.defineProperty(VertexBuffer, "UVKind", {
  26452. get: function () {
  26453. return VertexBuffer._UVKind;
  26454. },
  26455. enumerable: true,
  26456. configurable: true
  26457. });
  26458. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26459. get: function () {
  26460. return VertexBuffer._UV2Kind;
  26461. },
  26462. enumerable: true,
  26463. configurable: true
  26464. });
  26465. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26466. get: function () {
  26467. return VertexBuffer._UV3Kind;
  26468. },
  26469. enumerable: true,
  26470. configurable: true
  26471. });
  26472. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26473. get: function () {
  26474. return VertexBuffer._UV4Kind;
  26475. },
  26476. enumerable: true,
  26477. configurable: true
  26478. });
  26479. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26480. get: function () {
  26481. return VertexBuffer._UV5Kind;
  26482. },
  26483. enumerable: true,
  26484. configurable: true
  26485. });
  26486. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26487. get: function () {
  26488. return VertexBuffer._UV6Kind;
  26489. },
  26490. enumerable: true,
  26491. configurable: true
  26492. });
  26493. Object.defineProperty(VertexBuffer, "ColorKind", {
  26494. get: function () {
  26495. return VertexBuffer._ColorKind;
  26496. },
  26497. enumerable: true,
  26498. configurable: true
  26499. });
  26500. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26501. get: function () {
  26502. return VertexBuffer._MatricesIndicesKind;
  26503. },
  26504. enumerable: true,
  26505. configurable: true
  26506. });
  26507. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26508. get: function () {
  26509. return VertexBuffer._MatricesWeightsKind;
  26510. },
  26511. enumerable: true,
  26512. configurable: true
  26513. });
  26514. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26515. get: function () {
  26516. return VertexBuffer._MatricesIndicesExtraKind;
  26517. },
  26518. enumerable: true,
  26519. configurable: true
  26520. });
  26521. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26522. get: function () {
  26523. return VertexBuffer._MatricesWeightsExtraKind;
  26524. },
  26525. enumerable: true,
  26526. configurable: true
  26527. });
  26528. /**
  26529. * Deduces the stride given a kind.
  26530. * @param kind The kind string to deduce
  26531. * @returns The deduced stride
  26532. */
  26533. VertexBuffer.DeduceStride = function (kind) {
  26534. switch (kind) {
  26535. case VertexBuffer.UVKind:
  26536. case VertexBuffer.UV2Kind:
  26537. case VertexBuffer.UV3Kind:
  26538. case VertexBuffer.UV4Kind:
  26539. case VertexBuffer.UV5Kind:
  26540. case VertexBuffer.UV6Kind:
  26541. return 2;
  26542. case VertexBuffer.NormalKind:
  26543. case VertexBuffer.PositionKind:
  26544. return 3;
  26545. case VertexBuffer.ColorKind:
  26546. case VertexBuffer.MatricesIndicesKind:
  26547. case VertexBuffer.MatricesIndicesExtraKind:
  26548. case VertexBuffer.MatricesWeightsKind:
  26549. case VertexBuffer.MatricesWeightsExtraKind:
  26550. case VertexBuffer.TangentKind:
  26551. return 4;
  26552. default:
  26553. throw new Error("Invalid kind '" + kind + "'");
  26554. }
  26555. };
  26556. // Enums
  26557. VertexBuffer._PositionKind = "position";
  26558. VertexBuffer._NormalKind = "normal";
  26559. VertexBuffer._TangentKind = "tangent";
  26560. VertexBuffer._UVKind = "uv";
  26561. VertexBuffer._UV2Kind = "uv2";
  26562. VertexBuffer._UV3Kind = "uv3";
  26563. VertexBuffer._UV4Kind = "uv4";
  26564. VertexBuffer._UV5Kind = "uv5";
  26565. VertexBuffer._UV6Kind = "uv6";
  26566. VertexBuffer._ColorKind = "color";
  26567. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26568. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26569. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26570. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26571. return VertexBuffer;
  26572. }());
  26573. BABYLON.VertexBuffer = VertexBuffer;
  26574. })(BABYLON || (BABYLON = {}));
  26575. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26576. "use strict";
  26577. var BABYLON;
  26578. (function (BABYLON) {
  26579. /**
  26580. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26581. */
  26582. var DummyInternalTextureTracker = /** @class */ (function () {
  26583. function DummyInternalTextureTracker() {
  26584. /**
  26585. * Gets or set the previous tracker in the list
  26586. */
  26587. this.previous = null;
  26588. /**
  26589. * Gets or set the next tracker in the list
  26590. */
  26591. this.next = null;
  26592. }
  26593. return DummyInternalTextureTracker;
  26594. }());
  26595. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26596. })(BABYLON || (BABYLON = {}));
  26597. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26598. "use strict";
  26599. var BABYLON;
  26600. (function (BABYLON) {
  26601. /**
  26602. * Class used to store data associated with WebGL texture data for the engine
  26603. * This class should not be used directly
  26604. */
  26605. var InternalTexture = /** @class */ (function () {
  26606. /**
  26607. * Creates a new InternalTexture
  26608. * @param engine defines the engine to use
  26609. * @param dataSource defines the type of data that will be used
  26610. */
  26611. function InternalTexture(engine, dataSource) {
  26612. /**
  26613. * Observable called when the texture is loaded
  26614. */
  26615. this.onLoadedObservable = new BABYLON.Observable();
  26616. /**
  26617. * Gets or set the previous tracker in the list
  26618. */
  26619. this.previous = null;
  26620. /**
  26621. * Gets or set the next tracker in the list
  26622. */
  26623. this.next = null;
  26624. // Private
  26625. /** @ignore */
  26626. this._initialSlot = -1;
  26627. /** @ignore */
  26628. this._designatedSlot = -1;
  26629. /** @ignore */
  26630. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26631. /** @ignore */
  26632. this._comparisonFunction = 0;
  26633. /** @ignore */
  26634. this._references = 1;
  26635. this._engine = engine;
  26636. this._dataSource = dataSource;
  26637. this._webGLTexture = engine._createTexture();
  26638. }
  26639. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26640. /**
  26641. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26642. */
  26643. get: function () {
  26644. return this._dataSource;
  26645. },
  26646. enumerable: true,
  26647. configurable: true
  26648. });
  26649. /**
  26650. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26651. */
  26652. InternalTexture.prototype.incrementReferences = function () {
  26653. this._references++;
  26654. };
  26655. /**
  26656. * Change the size of the texture (not the size of the content)
  26657. * @param width defines the new width
  26658. * @param height defines the new height
  26659. * @param depth defines the new depth (1 by default)
  26660. */
  26661. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26662. if (depth === void 0) { depth = 1; }
  26663. this.width = width;
  26664. this.height = height;
  26665. this.depth = depth;
  26666. this.baseWidth = width;
  26667. this.baseHeight = height;
  26668. this.baseDepth = depth;
  26669. this._size = width * height * depth;
  26670. };
  26671. /** @ignore */
  26672. InternalTexture.prototype._rebuild = function () {
  26673. var _this = this;
  26674. var proxy;
  26675. this.isReady = false;
  26676. this._cachedCoordinatesMode = null;
  26677. this._cachedWrapU = null;
  26678. this._cachedWrapV = null;
  26679. this._cachedAnisotropicFilteringLevel = null;
  26680. switch (this._dataSource) {
  26681. case InternalTexture.DATASOURCE_TEMP:
  26682. return;
  26683. case InternalTexture.DATASOURCE_URL:
  26684. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26685. _this.isReady = true;
  26686. }, null, this._buffer, undefined, this.format);
  26687. proxy._swapAndDie(this);
  26688. return;
  26689. case InternalTexture.DATASOURCE_RAW:
  26690. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26691. proxy._swapAndDie(this);
  26692. this.isReady = true;
  26693. return;
  26694. case InternalTexture.DATASOURCE_RAW3D:
  26695. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26696. proxy._swapAndDie(this);
  26697. this.isReady = true;
  26698. return;
  26699. case InternalTexture.DATASOURCE_DYNAMIC:
  26700. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26701. proxy._swapAndDie(this);
  26702. // The engine will make sure to update content so no need to flag it as isReady = true
  26703. return;
  26704. case InternalTexture.DATASOURCE_RENDERTARGET:
  26705. var options = new BABYLON.RenderTargetCreationOptions();
  26706. options.generateDepthBuffer = this._generateDepthBuffer;
  26707. options.generateMipMaps = this.generateMipMaps;
  26708. options.generateStencilBuffer = this._generateStencilBuffer;
  26709. options.samplingMode = this.samplingMode;
  26710. options.type = this.type;
  26711. if (this.isCube) {
  26712. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26713. }
  26714. else {
  26715. var size = {
  26716. width: this.width,
  26717. height: this.height
  26718. };
  26719. proxy = this._engine.createRenderTargetTexture(size, options);
  26720. }
  26721. proxy._swapAndDie(this);
  26722. this.isReady = true;
  26723. return;
  26724. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26725. var depthTextureOptions = {
  26726. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26727. comparisonFunction: this._comparisonFunction,
  26728. generateStencil: this._generateStencilBuffer,
  26729. isCube: this.isCube
  26730. };
  26731. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26732. proxy._swapAndDie(this);
  26733. this.isReady = true;
  26734. return;
  26735. case InternalTexture.DATASOURCE_CUBE:
  26736. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26737. _this.isReady = true;
  26738. }, null, this.format, this._extension);
  26739. proxy._swapAndDie(this);
  26740. return;
  26741. case InternalTexture.DATASOURCE_CUBERAW:
  26742. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26743. proxy._swapAndDie(this);
  26744. this.isReady = true;
  26745. return;
  26746. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26747. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26748. if (proxy) {
  26749. proxy._swapAndDie(_this);
  26750. }
  26751. _this.isReady = true;
  26752. }, null, this.format, this._extension);
  26753. return;
  26754. }
  26755. };
  26756. InternalTexture.prototype._swapAndDie = function (target) {
  26757. target._webGLTexture = this._webGLTexture;
  26758. if (this._framebuffer) {
  26759. target._framebuffer = this._framebuffer;
  26760. }
  26761. if (this._depthStencilBuffer) {
  26762. target._depthStencilBuffer = this._depthStencilBuffer;
  26763. }
  26764. if (this._lodTextureHigh) {
  26765. if (target._lodTextureHigh) {
  26766. target._lodTextureHigh.dispose();
  26767. }
  26768. target._lodTextureHigh = this._lodTextureHigh;
  26769. }
  26770. if (this._lodTextureMid) {
  26771. if (target._lodTextureMid) {
  26772. target._lodTextureMid.dispose();
  26773. }
  26774. target._lodTextureMid = this._lodTextureMid;
  26775. }
  26776. if (this._lodTextureLow) {
  26777. if (target._lodTextureLow) {
  26778. target._lodTextureLow.dispose();
  26779. }
  26780. target._lodTextureLow = this._lodTextureLow;
  26781. }
  26782. var cache = this._engine.getLoadedTexturesCache();
  26783. var index = cache.indexOf(this);
  26784. if (index !== -1) {
  26785. cache.splice(index, 1);
  26786. }
  26787. };
  26788. /**
  26789. * Dispose the current allocated resources
  26790. */
  26791. InternalTexture.prototype.dispose = function () {
  26792. if (!this._webGLTexture) {
  26793. return;
  26794. }
  26795. this._references--;
  26796. if (this._references === 0) {
  26797. this._engine._releaseTexture(this);
  26798. this._webGLTexture = null;
  26799. this.previous = null;
  26800. this.next = null;
  26801. }
  26802. };
  26803. /**
  26804. * The source of the texture data is unknown
  26805. */
  26806. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26807. /**
  26808. * Texture data comes from an URL
  26809. */
  26810. InternalTexture.DATASOURCE_URL = 1;
  26811. /**
  26812. * Texture data is only used for temporary storage
  26813. */
  26814. InternalTexture.DATASOURCE_TEMP = 2;
  26815. /**
  26816. * Texture data comes from raw data (ArrayBuffer)
  26817. */
  26818. InternalTexture.DATASOURCE_RAW = 3;
  26819. /**
  26820. * Texture content is dynamic (video or dynamic texture)
  26821. */
  26822. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26823. /**
  26824. * Texture content is generated by rendering to it
  26825. */
  26826. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26827. /**
  26828. * Texture content is part of a multi render target process
  26829. */
  26830. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26831. /**
  26832. * Texture data comes from a cube data file
  26833. */
  26834. InternalTexture.DATASOURCE_CUBE = 7;
  26835. /**
  26836. * Texture data comes from a raw cube data
  26837. */
  26838. InternalTexture.DATASOURCE_CUBERAW = 8;
  26839. /**
  26840. * Texture data come from a prefiltered cube data file
  26841. */
  26842. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26843. /**
  26844. * Texture content is raw 3D data
  26845. */
  26846. InternalTexture.DATASOURCE_RAW3D = 10;
  26847. /**
  26848. * Texture content is a depth texture
  26849. */
  26850. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26851. return InternalTexture;
  26852. }());
  26853. BABYLON.InternalTexture = InternalTexture;
  26854. })(BABYLON || (BABYLON = {}));
  26855. //# sourceMappingURL=babylon.internalTexture.js.map
  26856. "use strict";
  26857. var BABYLON;
  26858. (function (BABYLON) {
  26859. var BaseTexture = /** @class */ (function () {
  26860. function BaseTexture(scene) {
  26861. this._hasAlpha = false;
  26862. this.getAlphaFromRGB = false;
  26863. this.level = 1;
  26864. this.coordinatesIndex = 0;
  26865. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26866. /**
  26867. * | Value | Type | Description |
  26868. * | ----- | ------------------ | ----------- |
  26869. * | 0 | CLAMP_ADDRESSMODE | |
  26870. * | 1 | WRAP_ADDRESSMODE | |
  26871. * | 2 | MIRROR_ADDRESSMODE | |
  26872. */
  26873. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26874. /**
  26875. * | Value | Type | Description |
  26876. * | ----- | ------------------ | ----------- |
  26877. * | 0 | CLAMP_ADDRESSMODE | |
  26878. * | 1 | WRAP_ADDRESSMODE | |
  26879. * | 2 | MIRROR_ADDRESSMODE | |
  26880. */
  26881. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26882. /**
  26883. * | Value | Type | Description |
  26884. * | ----- | ------------------ | ----------- |
  26885. * | 0 | CLAMP_ADDRESSMODE | |
  26886. * | 1 | WRAP_ADDRESSMODE | |
  26887. * | 2 | MIRROR_ADDRESSMODE | |
  26888. */
  26889. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26890. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26891. this.isCube = false;
  26892. this.is3D = false;
  26893. this.gammaSpace = true;
  26894. this.invertZ = false;
  26895. this.lodLevelInAlpha = false;
  26896. this.lodGenerationOffset = 0.0;
  26897. this.lodGenerationScale = 0.8;
  26898. this.isRenderTarget = false;
  26899. this.animations = new Array();
  26900. /**
  26901. * An event triggered when the texture is disposed.
  26902. * @type {BABYLON.Observable}
  26903. */
  26904. this.onDisposeObservable = new BABYLON.Observable();
  26905. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26906. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26907. if (this._scene) {
  26908. this._scene.textures.push(this);
  26909. }
  26910. this._uid = null;
  26911. }
  26912. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26913. get: function () {
  26914. return this._hasAlpha;
  26915. },
  26916. set: function (value) {
  26917. if (this._hasAlpha === value) {
  26918. return;
  26919. }
  26920. this._hasAlpha = value;
  26921. if (this._scene) {
  26922. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26923. }
  26924. },
  26925. enumerable: true,
  26926. configurable: true
  26927. });
  26928. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26929. get: function () {
  26930. return this._coordinatesMode;
  26931. },
  26932. /**
  26933. * How a texture is mapped.
  26934. *
  26935. * | Value | Type | Description |
  26936. * | ----- | ----------------------------------- | ----------- |
  26937. * | 0 | EXPLICIT_MODE | |
  26938. * | 1 | SPHERICAL_MODE | |
  26939. * | 2 | PLANAR_MODE | |
  26940. * | 3 | CUBIC_MODE | |
  26941. * | 4 | PROJECTION_MODE | |
  26942. * | 5 | SKYBOX_MODE | |
  26943. * | 6 | INVCUBIC_MODE | |
  26944. * | 7 | EQUIRECTANGULAR_MODE | |
  26945. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26946. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26947. */
  26948. set: function (value) {
  26949. if (this._coordinatesMode === value) {
  26950. return;
  26951. }
  26952. this._coordinatesMode = value;
  26953. if (this._scene) {
  26954. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26955. }
  26956. },
  26957. enumerable: true,
  26958. configurable: true
  26959. });
  26960. Object.defineProperty(BaseTexture.prototype, "uid", {
  26961. get: function () {
  26962. if (!this._uid) {
  26963. this._uid = BABYLON.Tools.RandomId();
  26964. }
  26965. return this._uid;
  26966. },
  26967. enumerable: true,
  26968. configurable: true
  26969. });
  26970. BaseTexture.prototype.toString = function () {
  26971. return this.name;
  26972. };
  26973. BaseTexture.prototype.getClassName = function () {
  26974. return "BaseTexture";
  26975. };
  26976. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26977. set: function (callback) {
  26978. if (this._onDisposeObserver) {
  26979. this.onDisposeObservable.remove(this._onDisposeObserver);
  26980. }
  26981. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26982. },
  26983. enumerable: true,
  26984. configurable: true
  26985. });
  26986. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26987. get: function () {
  26988. return true;
  26989. },
  26990. enumerable: true,
  26991. configurable: true
  26992. });
  26993. BaseTexture.prototype.getScene = function () {
  26994. return this._scene;
  26995. };
  26996. BaseTexture.prototype.getTextureMatrix = function () {
  26997. return BABYLON.Matrix.IdentityReadOnly;
  26998. };
  26999. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27000. return BABYLON.Matrix.IdentityReadOnly;
  27001. };
  27002. BaseTexture.prototype.getInternalTexture = function () {
  27003. return this._texture;
  27004. };
  27005. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27006. return !this.isBlocking || this.isReady();
  27007. };
  27008. BaseTexture.prototype.isReady = function () {
  27009. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27010. this.delayLoad();
  27011. return false;
  27012. }
  27013. if (this._texture) {
  27014. return this._texture.isReady;
  27015. }
  27016. return false;
  27017. };
  27018. BaseTexture.prototype.getSize = function () {
  27019. if (this._texture && this._texture.width) {
  27020. return new BABYLON.Size(this._texture.width, this._texture.height);
  27021. }
  27022. if (this._texture && this._texture._size) {
  27023. return new BABYLON.Size(this._texture._size, this._texture._size);
  27024. }
  27025. return BABYLON.Size.Zero();
  27026. };
  27027. BaseTexture.prototype.getBaseSize = function () {
  27028. if (!this.isReady() || !this._texture)
  27029. return BABYLON.Size.Zero();
  27030. if (this._texture._size) {
  27031. return new BABYLON.Size(this._texture._size, this._texture._size);
  27032. }
  27033. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27034. };
  27035. BaseTexture.prototype.scale = function (ratio) {
  27036. };
  27037. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27038. get: function () {
  27039. return false;
  27040. },
  27041. enumerable: true,
  27042. configurable: true
  27043. });
  27044. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27045. if (!this._scene) {
  27046. return null;
  27047. }
  27048. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27049. for (var index = 0; index < texturesCache.length; index++) {
  27050. var texturesCacheEntry = texturesCache[index];
  27051. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27052. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27053. texturesCacheEntry.incrementReferences();
  27054. return texturesCacheEntry;
  27055. }
  27056. }
  27057. }
  27058. return null;
  27059. };
  27060. BaseTexture.prototype._rebuild = function () {
  27061. };
  27062. BaseTexture.prototype.delayLoad = function () {
  27063. };
  27064. BaseTexture.prototype.clone = function () {
  27065. return null;
  27066. };
  27067. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27068. get: function () {
  27069. if (!this._texture) {
  27070. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27071. }
  27072. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27073. },
  27074. enumerable: true,
  27075. configurable: true
  27076. });
  27077. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27078. get: function () {
  27079. if (!this._texture) {
  27080. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27081. }
  27082. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27083. },
  27084. enumerable: true,
  27085. configurable: true
  27086. });
  27087. BaseTexture.prototype.readPixels = function (faceIndex) {
  27088. if (faceIndex === void 0) { faceIndex = 0; }
  27089. if (!this._texture) {
  27090. return null;
  27091. }
  27092. var size = this.getSize();
  27093. var scene = this.getScene();
  27094. if (!scene) {
  27095. return null;
  27096. }
  27097. var engine = scene.getEngine();
  27098. if (this._texture.isCube) {
  27099. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27100. }
  27101. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27102. };
  27103. BaseTexture.prototype.releaseInternalTexture = function () {
  27104. if (this._texture) {
  27105. this._texture.dispose();
  27106. this._texture = null;
  27107. }
  27108. };
  27109. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27110. get: function () {
  27111. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27112. return null;
  27113. }
  27114. if (!this._texture._sphericalPolynomial) {
  27115. this._texture._sphericalPolynomial =
  27116. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27117. }
  27118. return this._texture._sphericalPolynomial;
  27119. },
  27120. set: function (value) {
  27121. if (this._texture) {
  27122. this._texture._sphericalPolynomial = value;
  27123. }
  27124. },
  27125. enumerable: true,
  27126. configurable: true
  27127. });
  27128. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27129. get: function () {
  27130. if (this._texture) {
  27131. return this._texture._lodTextureHigh;
  27132. }
  27133. return null;
  27134. },
  27135. enumerable: true,
  27136. configurable: true
  27137. });
  27138. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27139. get: function () {
  27140. if (this._texture) {
  27141. return this._texture._lodTextureMid;
  27142. }
  27143. return null;
  27144. },
  27145. enumerable: true,
  27146. configurable: true
  27147. });
  27148. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27149. get: function () {
  27150. if (this._texture) {
  27151. return this._texture._lodTextureLow;
  27152. }
  27153. return null;
  27154. },
  27155. enumerable: true,
  27156. configurable: true
  27157. });
  27158. BaseTexture.prototype.dispose = function () {
  27159. if (!this._scene) {
  27160. return;
  27161. }
  27162. // Animations
  27163. this._scene.stopAnimation(this);
  27164. // Remove from scene
  27165. this._scene._removePendingData(this);
  27166. var index = this._scene.textures.indexOf(this);
  27167. if (index >= 0) {
  27168. this._scene.textures.splice(index, 1);
  27169. }
  27170. if (this._texture === undefined) {
  27171. return;
  27172. }
  27173. // Release
  27174. this.releaseInternalTexture();
  27175. // Callback
  27176. this.onDisposeObservable.notifyObservers(this);
  27177. this.onDisposeObservable.clear();
  27178. };
  27179. BaseTexture.prototype.serialize = function () {
  27180. if (!this.name) {
  27181. return null;
  27182. }
  27183. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27184. // Animations
  27185. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27186. return serializationObject;
  27187. };
  27188. BaseTexture.WhenAllReady = function (textures, callback) {
  27189. var numRemaining = textures.length;
  27190. if (numRemaining === 0) {
  27191. callback();
  27192. return;
  27193. }
  27194. var _loop_1 = function () {
  27195. texture = textures[i];
  27196. if (texture.isReady()) {
  27197. if (--numRemaining === 0) {
  27198. callback();
  27199. }
  27200. }
  27201. else {
  27202. onLoadObservable = texture.onLoadObservable;
  27203. var onLoadCallback_1 = function () {
  27204. onLoadObservable.removeCallback(onLoadCallback_1);
  27205. if (--numRemaining === 0) {
  27206. callback();
  27207. }
  27208. };
  27209. onLoadObservable.add(onLoadCallback_1);
  27210. }
  27211. };
  27212. var texture, onLoadObservable;
  27213. for (var i = 0; i < textures.length; i++) {
  27214. _loop_1();
  27215. }
  27216. };
  27217. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27218. __decorate([
  27219. BABYLON.serialize()
  27220. ], BaseTexture.prototype, "name", void 0);
  27221. __decorate([
  27222. BABYLON.serialize("hasAlpha")
  27223. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27224. __decorate([
  27225. BABYLON.serialize()
  27226. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27227. __decorate([
  27228. BABYLON.serialize()
  27229. ], BaseTexture.prototype, "level", void 0);
  27230. __decorate([
  27231. BABYLON.serialize()
  27232. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27233. __decorate([
  27234. BABYLON.serialize("coordinatesMode")
  27235. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27236. __decorate([
  27237. BABYLON.serialize()
  27238. ], BaseTexture.prototype, "wrapU", void 0);
  27239. __decorate([
  27240. BABYLON.serialize()
  27241. ], BaseTexture.prototype, "wrapV", void 0);
  27242. __decorate([
  27243. BABYLON.serialize()
  27244. ], BaseTexture.prototype, "wrapR", void 0);
  27245. __decorate([
  27246. BABYLON.serialize()
  27247. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27248. __decorate([
  27249. BABYLON.serialize()
  27250. ], BaseTexture.prototype, "isCube", void 0);
  27251. __decorate([
  27252. BABYLON.serialize()
  27253. ], BaseTexture.prototype, "is3D", void 0);
  27254. __decorate([
  27255. BABYLON.serialize()
  27256. ], BaseTexture.prototype, "gammaSpace", void 0);
  27257. __decorate([
  27258. BABYLON.serialize()
  27259. ], BaseTexture.prototype, "invertZ", void 0);
  27260. __decorate([
  27261. BABYLON.serialize()
  27262. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27263. __decorate([
  27264. BABYLON.serialize()
  27265. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27266. __decorate([
  27267. BABYLON.serialize()
  27268. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27269. __decorate([
  27270. BABYLON.serialize()
  27271. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27272. return BaseTexture;
  27273. }());
  27274. BABYLON.BaseTexture = BaseTexture;
  27275. })(BABYLON || (BABYLON = {}));
  27276. //# sourceMappingURL=babylon.baseTexture.js.map
  27277. "use strict";
  27278. var BABYLON;
  27279. (function (BABYLON) {
  27280. var Texture = /** @class */ (function (_super) {
  27281. __extends(Texture, _super);
  27282. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27283. if (noMipmap === void 0) { noMipmap = false; }
  27284. if (invertY === void 0) { invertY = true; }
  27285. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27286. if (onLoad === void 0) { onLoad = null; }
  27287. if (onError === void 0) { onError = null; }
  27288. if (buffer === void 0) { buffer = null; }
  27289. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27290. var _this = _super.call(this, scene) || this;
  27291. _this.uOffset = 0;
  27292. _this.vOffset = 0;
  27293. _this.uScale = 1.0;
  27294. _this.vScale = 1.0;
  27295. _this.uAng = 0;
  27296. _this.vAng = 0;
  27297. _this.wAng = 0;
  27298. _this._isBlocking = true;
  27299. _this.name = url || "";
  27300. _this.url = url;
  27301. _this._noMipmap = noMipmap;
  27302. _this._invertY = invertY;
  27303. _this._samplingMode = samplingMode;
  27304. _this._buffer = buffer;
  27305. _this._deleteBuffer = deleteBuffer;
  27306. if (format) {
  27307. _this._format = format;
  27308. }
  27309. scene = _this.getScene();
  27310. if (!scene) {
  27311. return _this;
  27312. }
  27313. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27314. var load = function () {
  27315. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27316. _this.onLoadObservable.notifyObservers(_this);
  27317. }
  27318. if (onLoad) {
  27319. onLoad();
  27320. }
  27321. if (!_this.isBlocking && scene) {
  27322. scene.resetCachedMaterial();
  27323. }
  27324. };
  27325. if (!_this.url) {
  27326. _this._delayedOnLoad = load;
  27327. _this._delayedOnError = onError;
  27328. return _this;
  27329. }
  27330. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27331. if (!_this._texture) {
  27332. if (!scene.useDelayedTextureLoading) {
  27333. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27334. if (deleteBuffer) {
  27335. delete _this._buffer;
  27336. }
  27337. }
  27338. else {
  27339. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27340. _this._delayedOnLoad = load;
  27341. _this._delayedOnError = onError;
  27342. }
  27343. }
  27344. else {
  27345. if (_this._texture.isReady) {
  27346. BABYLON.Tools.SetImmediate(function () { return load(); });
  27347. }
  27348. else {
  27349. _this._texture.onLoadedObservable.add(load);
  27350. }
  27351. }
  27352. return _this;
  27353. }
  27354. Object.defineProperty(Texture.prototype, "noMipmap", {
  27355. get: function () {
  27356. return this._noMipmap;
  27357. },
  27358. enumerable: true,
  27359. configurable: true
  27360. });
  27361. Object.defineProperty(Texture.prototype, "isBlocking", {
  27362. get: function () {
  27363. return this._isBlocking;
  27364. },
  27365. set: function (value) {
  27366. this._isBlocking = value;
  27367. },
  27368. enumerable: true,
  27369. configurable: true
  27370. });
  27371. Object.defineProperty(Texture.prototype, "samplingMode", {
  27372. get: function () {
  27373. return this._samplingMode;
  27374. },
  27375. enumerable: true,
  27376. configurable: true
  27377. });
  27378. Texture.prototype.updateURL = function (url) {
  27379. this.url = url;
  27380. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27381. this.delayLoad();
  27382. };
  27383. Texture.prototype.delayLoad = function () {
  27384. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27385. return;
  27386. }
  27387. var scene = this.getScene();
  27388. if (!scene) {
  27389. return;
  27390. }
  27391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27392. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27393. if (!this._texture) {
  27394. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27395. if (this._deleteBuffer) {
  27396. delete this._buffer;
  27397. }
  27398. }
  27399. else {
  27400. if (this._delayedOnLoad) {
  27401. if (this._texture.isReady) {
  27402. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27403. }
  27404. else {
  27405. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27406. }
  27407. }
  27408. }
  27409. this._delayedOnLoad = null;
  27410. this._delayedOnError = null;
  27411. };
  27412. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27413. if (!this._texture) {
  27414. return;
  27415. }
  27416. var scene = this.getScene();
  27417. if (!scene) {
  27418. return;
  27419. }
  27420. this._samplingMode = samplingMode;
  27421. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27422. };
  27423. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27424. x *= this.uScale;
  27425. y *= this.vScale;
  27426. x -= 0.5 * this.uScale;
  27427. y -= 0.5 * this.vScale;
  27428. z -= 0.5;
  27429. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27430. t.x += 0.5 * this.uScale + this.uOffset;
  27431. t.y += 0.5 * this.vScale + this.vOffset;
  27432. t.z += 0.5;
  27433. };
  27434. Texture.prototype.getTextureMatrix = function () {
  27435. var _this = this;
  27436. if (this.uOffset === this._cachedUOffset &&
  27437. this.vOffset === this._cachedVOffset &&
  27438. this.uScale === this._cachedUScale &&
  27439. this.vScale === this._cachedVScale &&
  27440. this.uAng === this._cachedUAng &&
  27441. this.vAng === this._cachedVAng &&
  27442. this.wAng === this._cachedWAng) {
  27443. return this._cachedTextureMatrix;
  27444. }
  27445. this._cachedUOffset = this.uOffset;
  27446. this._cachedVOffset = this.vOffset;
  27447. this._cachedUScale = this.uScale;
  27448. this._cachedVScale = this.vScale;
  27449. this._cachedUAng = this.uAng;
  27450. this._cachedVAng = this.vAng;
  27451. this._cachedWAng = this.wAng;
  27452. if (!this._cachedTextureMatrix) {
  27453. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27454. this._rowGenerationMatrix = new BABYLON.Matrix();
  27455. this._t0 = BABYLON.Vector3.Zero();
  27456. this._t1 = BABYLON.Vector3.Zero();
  27457. this._t2 = BABYLON.Vector3.Zero();
  27458. }
  27459. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27460. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27461. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27462. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27463. this._t1.subtractInPlace(this._t0);
  27464. this._t2.subtractInPlace(this._t0);
  27465. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27466. this._cachedTextureMatrix.m[0] = this._t1.x;
  27467. this._cachedTextureMatrix.m[1] = this._t1.y;
  27468. this._cachedTextureMatrix.m[2] = this._t1.z;
  27469. this._cachedTextureMatrix.m[4] = this._t2.x;
  27470. this._cachedTextureMatrix.m[5] = this._t2.y;
  27471. this._cachedTextureMatrix.m[6] = this._t2.z;
  27472. this._cachedTextureMatrix.m[8] = this._t0.x;
  27473. this._cachedTextureMatrix.m[9] = this._t0.y;
  27474. this._cachedTextureMatrix.m[10] = this._t0.z;
  27475. var scene = this.getScene();
  27476. if (!scene) {
  27477. return this._cachedTextureMatrix;
  27478. }
  27479. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27480. return mat.hasTexture(_this);
  27481. });
  27482. return this._cachedTextureMatrix;
  27483. };
  27484. Texture.prototype.getReflectionTextureMatrix = function () {
  27485. var _this = this;
  27486. var scene = this.getScene();
  27487. if (!scene) {
  27488. return this._cachedTextureMatrix;
  27489. }
  27490. if (this.uOffset === this._cachedUOffset &&
  27491. this.vOffset === this._cachedVOffset &&
  27492. this.uScale === this._cachedUScale &&
  27493. this.vScale === this._cachedVScale &&
  27494. this.coordinatesMode === this._cachedCoordinatesMode) {
  27495. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27496. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27497. return this._cachedTextureMatrix;
  27498. }
  27499. }
  27500. else {
  27501. return this._cachedTextureMatrix;
  27502. }
  27503. }
  27504. if (!this._cachedTextureMatrix) {
  27505. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27506. }
  27507. if (!this._projectionModeMatrix) {
  27508. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27509. }
  27510. this._cachedUOffset = this.uOffset;
  27511. this._cachedVOffset = this.vOffset;
  27512. this._cachedUScale = this.uScale;
  27513. this._cachedVScale = this.vScale;
  27514. this._cachedCoordinatesMode = this.coordinatesMode;
  27515. switch (this.coordinatesMode) {
  27516. case Texture.PLANAR_MODE:
  27517. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27518. this._cachedTextureMatrix[0] = this.uScale;
  27519. this._cachedTextureMatrix[5] = this.vScale;
  27520. this._cachedTextureMatrix[12] = this.uOffset;
  27521. this._cachedTextureMatrix[13] = this.vOffset;
  27522. break;
  27523. case Texture.PROJECTION_MODE:
  27524. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27525. this._projectionModeMatrix.m[0] = 0.5;
  27526. this._projectionModeMatrix.m[5] = -0.5;
  27527. this._projectionModeMatrix.m[10] = 0.0;
  27528. this._projectionModeMatrix.m[12] = 0.5;
  27529. this._projectionModeMatrix.m[13] = 0.5;
  27530. this._projectionModeMatrix.m[14] = 1.0;
  27531. this._projectionModeMatrix.m[15] = 1.0;
  27532. var projectionMatrix = scene.getProjectionMatrix();
  27533. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27534. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27535. break;
  27536. default:
  27537. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27538. break;
  27539. }
  27540. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27541. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27542. });
  27543. return this._cachedTextureMatrix;
  27544. };
  27545. Texture.prototype.clone = function () {
  27546. var _this = this;
  27547. return BABYLON.SerializationHelper.Clone(function () {
  27548. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27549. }, this);
  27550. };
  27551. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27552. get: function () {
  27553. if (!this._onLoadObservable) {
  27554. this._onLoadObservable = new BABYLON.Observable();
  27555. }
  27556. return this._onLoadObservable;
  27557. },
  27558. enumerable: true,
  27559. configurable: true
  27560. });
  27561. Texture.prototype.serialize = function () {
  27562. var serializationObject = _super.prototype.serialize.call(this);
  27563. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27564. serializationObject.base64String = this._buffer;
  27565. serializationObject.name = serializationObject.name.replace("data:", "");
  27566. }
  27567. return serializationObject;
  27568. };
  27569. Texture.prototype.getClassName = function () {
  27570. return "Texture";
  27571. };
  27572. Texture.prototype.dispose = function () {
  27573. _super.prototype.dispose.call(this);
  27574. if (this.onLoadObservable) {
  27575. this.onLoadObservable.clear();
  27576. this._onLoadObservable = null;
  27577. }
  27578. this._delayedOnLoad = null;
  27579. this._delayedOnError = null;
  27580. };
  27581. // Statics
  27582. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27583. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27584. if (onLoad === void 0) { onLoad = null; }
  27585. if (onError === void 0) { onError = null; }
  27586. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27587. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27588. };
  27589. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27590. if (parsedTexture.customType) {
  27591. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27592. // Update Sampling Mode
  27593. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27594. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27595. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27596. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27597. }
  27598. }
  27599. return parsedCustomTexture;
  27600. }
  27601. if (parsedTexture.isCube) {
  27602. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27603. }
  27604. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27605. return null;
  27606. }
  27607. var texture = BABYLON.SerializationHelper.Parse(function () {
  27608. var generateMipMaps = true;
  27609. if (parsedTexture.noMipmap) {
  27610. generateMipMaps = false;
  27611. }
  27612. if (parsedTexture.mirrorPlane) {
  27613. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27614. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27615. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27616. return mirrorTexture;
  27617. }
  27618. else if (parsedTexture.isRenderTarget) {
  27619. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27620. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27621. return renderTargetTexture;
  27622. }
  27623. else {
  27624. var texture;
  27625. if (parsedTexture.base64String) {
  27626. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27627. }
  27628. else {
  27629. var url = rootUrl + parsedTexture.name;
  27630. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27631. url = parsedTexture.url;
  27632. }
  27633. texture = new Texture(url, scene, !generateMipMaps);
  27634. }
  27635. return texture;
  27636. }
  27637. }, parsedTexture, scene);
  27638. // Update Sampling Mode
  27639. if (parsedTexture.samplingMode) {
  27640. var sampling = parsedTexture.samplingMode;
  27641. if (texture._samplingMode !== sampling) {
  27642. texture.updateSamplingMode(sampling);
  27643. }
  27644. }
  27645. // Animations
  27646. if (parsedTexture.animations) {
  27647. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27648. var parsedAnimation = parsedTexture.animations[animationIndex];
  27649. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27650. }
  27651. }
  27652. return texture;
  27653. };
  27654. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27655. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27656. if (noMipmap === void 0) { noMipmap = false; }
  27657. if (invertY === void 0) { invertY = true; }
  27658. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27659. if (onLoad === void 0) { onLoad = null; }
  27660. if (onError === void 0) { onError = null; }
  27661. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27662. if (name.substr(0, 5) !== "data:") {
  27663. name = "data:" + name;
  27664. }
  27665. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27666. };
  27667. // Constants
  27668. Texture.NEAREST_SAMPLINGMODE = 1;
  27669. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27670. Texture.BILINEAR_SAMPLINGMODE = 2;
  27671. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27672. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27673. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27674. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27675. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27676. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27677. Texture.NEAREST_LINEAR = 7;
  27678. Texture.NEAREST_NEAREST = 8;
  27679. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27680. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27681. Texture.LINEAR_LINEAR = 11;
  27682. Texture.LINEAR_NEAREST = 12;
  27683. Texture.EXPLICIT_MODE = 0;
  27684. Texture.SPHERICAL_MODE = 1;
  27685. Texture.PLANAR_MODE = 2;
  27686. Texture.CUBIC_MODE = 3;
  27687. Texture.PROJECTION_MODE = 4;
  27688. Texture.SKYBOX_MODE = 5;
  27689. Texture.INVCUBIC_MODE = 6;
  27690. Texture.EQUIRECTANGULAR_MODE = 7;
  27691. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27692. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27693. Texture.CLAMP_ADDRESSMODE = 0;
  27694. Texture.WRAP_ADDRESSMODE = 1;
  27695. Texture.MIRROR_ADDRESSMODE = 2;
  27696. /**
  27697. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27698. */
  27699. Texture.UseSerializedUrlIfAny = false;
  27700. __decorate([
  27701. BABYLON.serialize()
  27702. ], Texture.prototype, "url", void 0);
  27703. __decorate([
  27704. BABYLON.serialize()
  27705. ], Texture.prototype, "uOffset", void 0);
  27706. __decorate([
  27707. BABYLON.serialize()
  27708. ], Texture.prototype, "vOffset", void 0);
  27709. __decorate([
  27710. BABYLON.serialize()
  27711. ], Texture.prototype, "uScale", void 0);
  27712. __decorate([
  27713. BABYLON.serialize()
  27714. ], Texture.prototype, "vScale", void 0);
  27715. __decorate([
  27716. BABYLON.serialize()
  27717. ], Texture.prototype, "uAng", void 0);
  27718. __decorate([
  27719. BABYLON.serialize()
  27720. ], Texture.prototype, "vAng", void 0);
  27721. __decorate([
  27722. BABYLON.serialize()
  27723. ], Texture.prototype, "wAng", void 0);
  27724. __decorate([
  27725. BABYLON.serialize()
  27726. ], Texture.prototype, "isBlocking", null);
  27727. return Texture;
  27728. }(BABYLON.BaseTexture));
  27729. BABYLON.Texture = Texture;
  27730. })(BABYLON || (BABYLON = {}));
  27731. //# sourceMappingURL=babylon.texture.js.map
  27732. "use strict";
  27733. var BABYLON;
  27734. (function (BABYLON) {
  27735. var _InstancesBatch = /** @class */ (function () {
  27736. function _InstancesBatch() {
  27737. this.mustReturn = false;
  27738. this.visibleInstances = new Array();
  27739. this.renderSelf = new Array();
  27740. }
  27741. return _InstancesBatch;
  27742. }());
  27743. BABYLON._InstancesBatch = _InstancesBatch;
  27744. var Mesh = /** @class */ (function (_super) {
  27745. __extends(Mesh, _super);
  27746. /**
  27747. * @constructor
  27748. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27749. * @param {Scene} scene The scene to add this mesh to.
  27750. * @param {Node} parent The parent of this mesh, if it has one
  27751. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27752. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27753. * When false, achieved by calling a clone(), also passing False.
  27754. * This will make creation of children, recursive.
  27755. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27756. */
  27757. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27758. if (scene === void 0) { scene = null; }
  27759. if (parent === void 0) { parent = null; }
  27760. if (source === void 0) { source = null; }
  27761. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27762. var _this = _super.call(this, name, scene) || this;
  27763. // Events
  27764. /**
  27765. * An event triggered before rendering the mesh
  27766. * @type {BABYLON.Observable}
  27767. */
  27768. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27769. /**
  27770. * An event triggered after rendering the mesh
  27771. * @type {BABYLON.Observable}
  27772. */
  27773. _this.onAfterRenderObservable = new BABYLON.Observable();
  27774. /**
  27775. * An event triggered before drawing the mesh
  27776. * @type {BABYLON.Observable}
  27777. */
  27778. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27779. // Members
  27780. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27781. _this.instances = new Array();
  27782. _this._LODLevels = new Array();
  27783. _this._visibleInstances = {};
  27784. _this._renderIdForInstances = new Array();
  27785. _this._batchCache = new _InstancesBatch();
  27786. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27787. // Use by builder only to know what orientation were the mesh build in.
  27788. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27789. _this.overrideMaterialSideOrientation = null;
  27790. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27791. // Will be used to save a source mesh reference, If any
  27792. _this._source = null;
  27793. scene = _this.getScene();
  27794. if (source) {
  27795. // Source mesh
  27796. _this._source = source;
  27797. // Geometry
  27798. if (source._geometry) {
  27799. source._geometry.applyToMesh(_this);
  27800. }
  27801. // Deep copy
  27802. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27803. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27804. // Metadata
  27805. if (source.metadata && source.metadata.clone) {
  27806. _this.metadata = source.metadata.clone();
  27807. }
  27808. else {
  27809. _this.metadata = source.metadata;
  27810. }
  27811. // Tags
  27812. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27813. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27814. }
  27815. // Parent
  27816. _this.parent = source.parent;
  27817. // Pivot
  27818. _this.setPivotMatrix(source.getPivotMatrix());
  27819. _this.id = name + "." + source.id;
  27820. // Material
  27821. _this.material = source.material;
  27822. var index;
  27823. if (!doNotCloneChildren) {
  27824. // Children
  27825. var directDescendants = source.getDescendants(true);
  27826. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27827. var child = directDescendants[index_1];
  27828. if (child.clone) {
  27829. child.clone(name + "." + child.name, _this);
  27830. }
  27831. }
  27832. }
  27833. // Physics clone
  27834. var physicsEngine = _this.getScene().getPhysicsEngine();
  27835. if (clonePhysicsImpostor && physicsEngine) {
  27836. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27837. if (impostor) {
  27838. _this.physicsImpostor = impostor.clone(_this);
  27839. }
  27840. }
  27841. // Particles
  27842. for (index = 0; index < scene.particleSystems.length; index++) {
  27843. var system = scene.particleSystems[index];
  27844. if (system.emitter === source) {
  27845. system.clone(system.name, _this);
  27846. }
  27847. }
  27848. _this.computeWorldMatrix(true);
  27849. }
  27850. // Parent
  27851. if (parent !== null) {
  27852. _this.parent = parent;
  27853. }
  27854. return _this;
  27855. }
  27856. Object.defineProperty(Mesh, "FRONTSIDE", {
  27857. /**
  27858. * Mesh side orientation : usually the external or front surface
  27859. */
  27860. get: function () {
  27861. return Mesh._FRONTSIDE;
  27862. },
  27863. enumerable: true,
  27864. configurable: true
  27865. });
  27866. Object.defineProperty(Mesh, "BACKSIDE", {
  27867. /**
  27868. * Mesh side orientation : usually the internal or back surface
  27869. */
  27870. get: function () {
  27871. return Mesh._BACKSIDE;
  27872. },
  27873. enumerable: true,
  27874. configurable: true
  27875. });
  27876. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27877. /**
  27878. * Mesh side orientation : both internal and external or front and back surfaces
  27879. */
  27880. get: function () {
  27881. return Mesh._DOUBLESIDE;
  27882. },
  27883. enumerable: true,
  27884. configurable: true
  27885. });
  27886. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27887. /**
  27888. * Mesh side orientation : by default, `FRONTSIDE`
  27889. */
  27890. get: function () {
  27891. return Mesh._DEFAULTSIDE;
  27892. },
  27893. enumerable: true,
  27894. configurable: true
  27895. });
  27896. Object.defineProperty(Mesh, "NO_CAP", {
  27897. /**
  27898. * Mesh cap setting : no cap
  27899. */
  27900. get: function () {
  27901. return Mesh._NO_CAP;
  27902. },
  27903. enumerable: true,
  27904. configurable: true
  27905. });
  27906. Object.defineProperty(Mesh, "CAP_START", {
  27907. /**
  27908. * Mesh cap setting : one cap at the beginning of the mesh
  27909. */
  27910. get: function () {
  27911. return Mesh._CAP_START;
  27912. },
  27913. enumerable: true,
  27914. configurable: true
  27915. });
  27916. Object.defineProperty(Mesh, "CAP_END", {
  27917. /**
  27918. * Mesh cap setting : one cap at the end of the mesh
  27919. */
  27920. get: function () {
  27921. return Mesh._CAP_END;
  27922. },
  27923. enumerable: true,
  27924. configurable: true
  27925. });
  27926. Object.defineProperty(Mesh, "CAP_ALL", {
  27927. /**
  27928. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27929. */
  27930. get: function () {
  27931. return Mesh._CAP_ALL;
  27932. },
  27933. enumerable: true,
  27934. configurable: true
  27935. });
  27936. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27937. set: function (callback) {
  27938. if (this._onBeforeDrawObserver) {
  27939. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27940. }
  27941. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27942. },
  27943. enumerable: true,
  27944. configurable: true
  27945. });
  27946. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27947. get: function () {
  27948. return this._morphTargetManager;
  27949. },
  27950. set: function (value) {
  27951. if (this._morphTargetManager === value) {
  27952. return;
  27953. }
  27954. this._morphTargetManager = value;
  27955. this._syncGeometryWithMorphTargetManager();
  27956. },
  27957. enumerable: true,
  27958. configurable: true
  27959. });
  27960. Object.defineProperty(Mesh.prototype, "source", {
  27961. get: function () {
  27962. return this._source;
  27963. },
  27964. enumerable: true,
  27965. configurable: true
  27966. });
  27967. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27968. get: function () {
  27969. return this._unIndexed;
  27970. },
  27971. set: function (value) {
  27972. if (this._unIndexed !== value) {
  27973. this._unIndexed = value;
  27974. this._markSubMeshesAsAttributesDirty();
  27975. }
  27976. },
  27977. enumerable: true,
  27978. configurable: true
  27979. });
  27980. // Methods
  27981. /**
  27982. * Returns the string "Mesh".
  27983. */
  27984. Mesh.prototype.getClassName = function () {
  27985. return "Mesh";
  27986. };
  27987. /**
  27988. * Returns a string.
  27989. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27990. */
  27991. Mesh.prototype.toString = function (fullDetails) {
  27992. var ret = _super.prototype.toString.call(this, fullDetails);
  27993. ret += ", n vertices: " + this.getTotalVertices();
  27994. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27995. if (this.animations) {
  27996. for (var i = 0; i < this.animations.length; i++) {
  27997. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27998. }
  27999. }
  28000. if (fullDetails) {
  28001. if (this._geometry) {
  28002. var ib = this.getIndices();
  28003. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28004. if (vb && ib) {
  28005. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28006. }
  28007. }
  28008. else {
  28009. ret += ", flat shading: UNKNOWN";
  28010. }
  28011. }
  28012. return ret;
  28013. };
  28014. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28015. /**
  28016. * True if the mesh has some Levels Of Details (LOD).
  28017. * Returns a boolean.
  28018. */
  28019. get: function () {
  28020. return this._LODLevels.length > 0;
  28021. },
  28022. enumerable: true,
  28023. configurable: true
  28024. });
  28025. /**
  28026. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28027. * @returns an array of {BABYLON.MeshLODLevel}
  28028. */
  28029. Mesh.prototype.getLODLevels = function () {
  28030. return this._LODLevels;
  28031. };
  28032. Mesh.prototype._sortLODLevels = function () {
  28033. this._LODLevels.sort(function (a, b) {
  28034. if (a.distance < b.distance) {
  28035. return 1;
  28036. }
  28037. if (a.distance > b.distance) {
  28038. return -1;
  28039. }
  28040. return 0;
  28041. });
  28042. };
  28043. /**
  28044. * Add a mesh as LOD level triggered at the given distance.
  28045. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28046. * @param {number} distance The distance from the center of the object to show this level
  28047. * @param {Mesh} mesh The mesh to be added as LOD level
  28048. * @return {Mesh} This mesh (for chaining)
  28049. */
  28050. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28051. if (mesh && mesh._masterMesh) {
  28052. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28053. return this;
  28054. }
  28055. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28056. this._LODLevels.push(level);
  28057. if (mesh) {
  28058. mesh._masterMesh = this;
  28059. }
  28060. this._sortLODLevels();
  28061. return this;
  28062. };
  28063. /**
  28064. * Returns the LOD level mesh at the passed distance or null if not found.
  28065. * It is related to the method `addLODLevel(distance, mesh)`.
  28066. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28067. * Returns an object Mesh or `null`.
  28068. */
  28069. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28070. for (var index = 0; index < this._LODLevels.length; index++) {
  28071. var level = this._LODLevels[index];
  28072. if (level.distance === distance) {
  28073. return level.mesh;
  28074. }
  28075. }
  28076. return null;
  28077. };
  28078. /**
  28079. * Remove a mesh from the LOD array
  28080. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28081. * @param {Mesh} mesh The mesh to be removed.
  28082. * @return {Mesh} This mesh (for chaining)
  28083. */
  28084. Mesh.prototype.removeLODLevel = function (mesh) {
  28085. for (var index = 0; index < this._LODLevels.length; index++) {
  28086. if (this._LODLevels[index].mesh === mesh) {
  28087. this._LODLevels.splice(index, 1);
  28088. if (mesh) {
  28089. mesh._masterMesh = null;
  28090. }
  28091. }
  28092. }
  28093. this._sortLODLevels();
  28094. return this;
  28095. };
  28096. /**
  28097. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28098. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28099. */
  28100. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28101. if (!this._LODLevels || this._LODLevels.length === 0) {
  28102. return this;
  28103. }
  28104. var bSphere;
  28105. if (boundingSphere) {
  28106. bSphere = boundingSphere;
  28107. }
  28108. else {
  28109. var boundingInfo = this.getBoundingInfo();
  28110. bSphere = boundingInfo.boundingSphere;
  28111. }
  28112. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28113. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28114. if (this.onLODLevelSelection) {
  28115. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28116. }
  28117. return this;
  28118. }
  28119. for (var index = 0; index < this._LODLevels.length; index++) {
  28120. var level = this._LODLevels[index];
  28121. if (level.distance < distanceToCamera) {
  28122. if (level.mesh) {
  28123. level.mesh._preActivate();
  28124. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28125. }
  28126. if (this.onLODLevelSelection) {
  28127. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28128. }
  28129. return level.mesh;
  28130. }
  28131. }
  28132. if (this.onLODLevelSelection) {
  28133. this.onLODLevelSelection(distanceToCamera, this, this);
  28134. }
  28135. return this;
  28136. };
  28137. Object.defineProperty(Mesh.prototype, "geometry", {
  28138. /**
  28139. * Returns the mesh internal Geometry object.
  28140. */
  28141. get: function () {
  28142. return this._geometry;
  28143. },
  28144. enumerable: true,
  28145. configurable: true
  28146. });
  28147. /**
  28148. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28149. */
  28150. Mesh.prototype.getTotalVertices = function () {
  28151. if (this._geometry === null || this._geometry === undefined) {
  28152. return 0;
  28153. }
  28154. return this._geometry.getTotalVertices();
  28155. };
  28156. /**
  28157. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28158. * 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.
  28159. * You can force the copy with forceCopy === true
  28160. * Returns null if the mesh has no geometry or no vertex buffer.
  28161. * Possible `kind` values :
  28162. * - BABYLON.VertexBuffer.PositionKind
  28163. * - BABYLON.VertexBuffer.UVKind
  28164. * - BABYLON.VertexBuffer.UV2Kind
  28165. * - BABYLON.VertexBuffer.UV3Kind
  28166. * - BABYLON.VertexBuffer.UV4Kind
  28167. * - BABYLON.VertexBuffer.UV5Kind
  28168. * - BABYLON.VertexBuffer.UV6Kind
  28169. * - BABYLON.VertexBuffer.ColorKind
  28170. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28171. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28172. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28173. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28174. */
  28175. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28176. if (!this._geometry) {
  28177. return null;
  28178. }
  28179. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28180. };
  28181. /**
  28182. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28183. * Returns `null` if the mesh has no geometry.
  28184. * Possible `kind` values :
  28185. * - BABYLON.VertexBuffer.PositionKind
  28186. * - BABYLON.VertexBuffer.UVKind
  28187. * - BABYLON.VertexBuffer.UV2Kind
  28188. * - BABYLON.VertexBuffer.UV3Kind
  28189. * - BABYLON.VertexBuffer.UV4Kind
  28190. * - BABYLON.VertexBuffer.UV5Kind
  28191. * - BABYLON.VertexBuffer.UV6Kind
  28192. * - BABYLON.VertexBuffer.ColorKind
  28193. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28194. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28195. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28196. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28197. */
  28198. Mesh.prototype.getVertexBuffer = function (kind) {
  28199. if (!this._geometry) {
  28200. return null;
  28201. }
  28202. return this._geometry.getVertexBuffer(kind);
  28203. };
  28204. /**
  28205. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28206. * Possible `kind` values :
  28207. * - BABYLON.VertexBuffer.PositionKind
  28208. * - BABYLON.VertexBuffer.UVKind
  28209. * - BABYLON.VertexBuffer.UV2Kind
  28210. * - BABYLON.VertexBuffer.UV3Kind
  28211. * - BABYLON.VertexBuffer.UV4Kind
  28212. * - BABYLON.VertexBuffer.UV5Kind
  28213. * - BABYLON.VertexBuffer.UV6Kind
  28214. * - BABYLON.VertexBuffer.ColorKind
  28215. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28216. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28217. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28218. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28219. */
  28220. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28221. if (!this._geometry) {
  28222. if (this._delayInfo) {
  28223. return this._delayInfo.indexOf(kind) !== -1;
  28224. }
  28225. return false;
  28226. }
  28227. return this._geometry.isVerticesDataPresent(kind);
  28228. };
  28229. /**
  28230. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28231. * Possible `kind` values :
  28232. * - BABYLON.VertexBuffer.PositionKind
  28233. * - BABYLON.VertexBuffer.UVKind
  28234. * - BABYLON.VertexBuffer.UV2Kind
  28235. * - BABYLON.VertexBuffer.UV3Kind
  28236. * - BABYLON.VertexBuffer.UV4Kind
  28237. * - BABYLON.VertexBuffer.UV5Kind
  28238. * - BABYLON.VertexBuffer.UV6Kind
  28239. * - BABYLON.VertexBuffer.ColorKind
  28240. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28241. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28242. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28243. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28244. */
  28245. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28246. if (!this._geometry) {
  28247. if (this._delayInfo) {
  28248. return this._delayInfo.indexOf(kind) !== -1;
  28249. }
  28250. return false;
  28251. }
  28252. return this._geometry.isVertexBufferUpdatable(kind);
  28253. };
  28254. /**
  28255. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28256. * Possible `kind` values :
  28257. * - BABYLON.VertexBuffer.PositionKind
  28258. * - BABYLON.VertexBuffer.UVKind
  28259. * - BABYLON.VertexBuffer.UV2Kind
  28260. * - BABYLON.VertexBuffer.UV3Kind
  28261. * - BABYLON.VertexBuffer.UV4Kind
  28262. * - BABYLON.VertexBuffer.UV5Kind
  28263. * - BABYLON.VertexBuffer.UV6Kind
  28264. * - BABYLON.VertexBuffer.ColorKind
  28265. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28266. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28267. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28268. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28269. */
  28270. Mesh.prototype.getVerticesDataKinds = function () {
  28271. if (!this._geometry) {
  28272. var result = new Array();
  28273. if (this._delayInfo) {
  28274. this._delayInfo.forEach(function (kind, index, array) {
  28275. result.push(kind);
  28276. });
  28277. }
  28278. return result;
  28279. }
  28280. return this._geometry.getVerticesDataKinds();
  28281. };
  28282. /**
  28283. * Returns a positive integer : the total number of indices in this mesh geometry.
  28284. * Returns zero if the mesh has no geometry.
  28285. */
  28286. Mesh.prototype.getTotalIndices = function () {
  28287. if (!this._geometry) {
  28288. return 0;
  28289. }
  28290. return this._geometry.getTotalIndices();
  28291. };
  28292. /**
  28293. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28294. * 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.
  28295. * Returns an empty array if the mesh has no geometry.
  28296. */
  28297. Mesh.prototype.getIndices = function (copyWhenShared) {
  28298. if (!this._geometry) {
  28299. return [];
  28300. }
  28301. return this._geometry.getIndices(copyWhenShared);
  28302. };
  28303. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28304. get: function () {
  28305. return this._masterMesh !== null && this._masterMesh !== undefined;
  28306. },
  28307. enumerable: true,
  28308. configurable: true
  28309. });
  28310. /**
  28311. * Determine if the current mesh is ready to be rendered
  28312. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28313. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28314. * @returns true if all associated assets are ready (material, textures, shaders)
  28315. */
  28316. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28317. if (completeCheck === void 0) { completeCheck = false; }
  28318. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28319. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28320. return false;
  28321. }
  28322. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28323. return false;
  28324. }
  28325. if (!this.subMeshes || this.subMeshes.length === 0) {
  28326. return true;
  28327. }
  28328. if (!completeCheck) {
  28329. return true;
  28330. }
  28331. var engine = this.getEngine();
  28332. var scene = this.getScene();
  28333. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28334. this.computeWorldMatrix();
  28335. var mat = this.material || scene.defaultMaterial;
  28336. if (mat) {
  28337. if (mat.storeEffectOnSubMeshes) {
  28338. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28339. var subMesh = _a[_i];
  28340. var effectiveMaterial = subMesh.getMaterial();
  28341. if (effectiveMaterial) {
  28342. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28343. return false;
  28344. }
  28345. }
  28346. }
  28347. }
  28348. else {
  28349. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28350. return false;
  28351. }
  28352. }
  28353. }
  28354. // Shadows
  28355. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28356. var light = _c[_b];
  28357. var generator = light.getShadowGenerator();
  28358. if (generator) {
  28359. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28360. var subMesh = _e[_d];
  28361. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28362. return false;
  28363. }
  28364. }
  28365. }
  28366. }
  28367. // LOD
  28368. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28369. var lod = _g[_f];
  28370. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28371. return false;
  28372. }
  28373. }
  28374. return true;
  28375. };
  28376. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28377. /**
  28378. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28379. * This property is pertinent only for updatable parametric shapes.
  28380. */
  28381. get: function () {
  28382. return this._areNormalsFrozen;
  28383. },
  28384. enumerable: true,
  28385. configurable: true
  28386. });
  28387. /**
  28388. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28389. * It has no effect at all on other shapes.
  28390. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28391. * Returns the Mesh.
  28392. */
  28393. Mesh.prototype.freezeNormals = function () {
  28394. this._areNormalsFrozen = true;
  28395. return this;
  28396. };
  28397. /**
  28398. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28399. * It has no effect at all on other shapes.
  28400. * It reactivates the mesh normals computation if it was previously frozen.
  28401. * Returns the Mesh.
  28402. */
  28403. Mesh.prototype.unfreezeNormals = function () {
  28404. this._areNormalsFrozen = false;
  28405. return this;
  28406. };
  28407. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28408. /**
  28409. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28410. */
  28411. set: function (count) {
  28412. this._overridenInstanceCount = count;
  28413. },
  28414. enumerable: true,
  28415. configurable: true
  28416. });
  28417. // Methods
  28418. Mesh.prototype._preActivate = function () {
  28419. var sceneRenderId = this.getScene().getRenderId();
  28420. if (this._preActivateId === sceneRenderId) {
  28421. return this;
  28422. }
  28423. this._preActivateId = sceneRenderId;
  28424. this._visibleInstances = null;
  28425. return this;
  28426. };
  28427. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28428. if (this._visibleInstances) {
  28429. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28430. }
  28431. return this;
  28432. };
  28433. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28434. if (!this._visibleInstances) {
  28435. this._visibleInstances = {};
  28436. this._visibleInstances.defaultRenderId = renderId;
  28437. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28438. }
  28439. if (!this._visibleInstances[renderId]) {
  28440. this._visibleInstances[renderId] = new Array();
  28441. }
  28442. this._visibleInstances[renderId].push(instance);
  28443. return this;
  28444. };
  28445. /**
  28446. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28447. * This means the mesh underlying bounding box and sphere are recomputed.
  28448. * Returns the Mesh.
  28449. */
  28450. Mesh.prototype.refreshBoundingInfo = function () {
  28451. return this._refreshBoundingInfo(false);
  28452. };
  28453. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28454. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28455. return this;
  28456. }
  28457. var data = this._getPositionData(applySkeleton);
  28458. if (data) {
  28459. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28460. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28461. }
  28462. if (this.subMeshes) {
  28463. for (var index = 0; index < this.subMeshes.length; index++) {
  28464. this.subMeshes[index].refreshBoundingInfo();
  28465. }
  28466. }
  28467. this._updateBoundingInfo();
  28468. return this;
  28469. };
  28470. Mesh.prototype._getPositionData = function (applySkeleton) {
  28471. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28472. if (data && applySkeleton && this.skeleton) {
  28473. data = BABYLON.Tools.Slice(data);
  28474. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28475. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28476. if (matricesWeightsData && matricesIndicesData) {
  28477. var needExtras = this.numBoneInfluencers > 4;
  28478. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28479. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28480. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28481. var tempVector = BABYLON.Tmp.Vector3[0];
  28482. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28483. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28484. var matWeightIdx = 0;
  28485. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28486. finalMatrix.reset();
  28487. var inf;
  28488. var weight;
  28489. for (inf = 0; inf < 4; inf++) {
  28490. weight = matricesWeightsData[matWeightIdx + inf];
  28491. if (weight <= 0)
  28492. break;
  28493. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28494. finalMatrix.addToSelf(tempMatrix);
  28495. }
  28496. if (needExtras) {
  28497. for (inf = 0; inf < 4; inf++) {
  28498. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28499. if (weight <= 0)
  28500. break;
  28501. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28502. finalMatrix.addToSelf(tempMatrix);
  28503. }
  28504. }
  28505. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28506. tempVector.toArray(data, index);
  28507. }
  28508. }
  28509. }
  28510. return data;
  28511. };
  28512. Mesh.prototype._createGlobalSubMesh = function (force) {
  28513. var totalVertices = this.getTotalVertices();
  28514. if (!totalVertices || !this.getIndices()) {
  28515. return null;
  28516. }
  28517. // Check if we need to recreate the submeshes
  28518. if (this.subMeshes && this.subMeshes.length > 0) {
  28519. var ib = this.getIndices();
  28520. if (!ib) {
  28521. return null;
  28522. }
  28523. var totalIndices = ib.length;
  28524. var needToRecreate = false;
  28525. if (force) {
  28526. needToRecreate = true;
  28527. }
  28528. else {
  28529. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28530. var submesh = _a[_i];
  28531. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28532. needToRecreate = true;
  28533. break;
  28534. }
  28535. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28536. needToRecreate = true;
  28537. break;
  28538. }
  28539. }
  28540. }
  28541. if (!needToRecreate) {
  28542. return this.subMeshes[0];
  28543. }
  28544. }
  28545. this.releaseSubMeshes();
  28546. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28547. };
  28548. Mesh.prototype.subdivide = function (count) {
  28549. if (count < 1) {
  28550. return;
  28551. }
  28552. var totalIndices = this.getTotalIndices();
  28553. var subdivisionSize = (totalIndices / count) | 0;
  28554. var offset = 0;
  28555. // Ensure that subdivisionSize is a multiple of 3
  28556. while (subdivisionSize % 3 !== 0) {
  28557. subdivisionSize++;
  28558. }
  28559. this.releaseSubMeshes();
  28560. for (var index = 0; index < count; index++) {
  28561. if (offset >= totalIndices) {
  28562. break;
  28563. }
  28564. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28565. offset += subdivisionSize;
  28566. }
  28567. this.synchronizeInstances();
  28568. };
  28569. /**
  28570. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28571. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28572. * The `data` are either a numeric array either a Float32Array.
  28573. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28574. * 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).
  28575. * Note that a new underlying VertexBuffer object is created each call.
  28576. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28577. *
  28578. * Possible `kind` values :
  28579. * - BABYLON.VertexBuffer.PositionKind
  28580. * - BABYLON.VertexBuffer.UVKind
  28581. * - BABYLON.VertexBuffer.UV2Kind
  28582. * - BABYLON.VertexBuffer.UV3Kind
  28583. * - BABYLON.VertexBuffer.UV4Kind
  28584. * - BABYLON.VertexBuffer.UV5Kind
  28585. * - BABYLON.VertexBuffer.UV6Kind
  28586. * - BABYLON.VertexBuffer.ColorKind
  28587. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28588. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28589. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28590. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28591. *
  28592. * Returns the Mesh.
  28593. */
  28594. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28595. if (updatable === void 0) { updatable = false; }
  28596. if (!this._geometry) {
  28597. var vertexData = new BABYLON.VertexData();
  28598. vertexData.set(data, kind);
  28599. var scene = this.getScene();
  28600. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28601. }
  28602. else {
  28603. this._geometry.setVerticesData(kind, data, updatable, stride);
  28604. }
  28605. return this;
  28606. };
  28607. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28608. if (updatable === void 0) { updatable = true; }
  28609. var vb = this.getVertexBuffer(kind);
  28610. if (!vb || vb.isUpdatable() === updatable) {
  28611. return;
  28612. }
  28613. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28614. };
  28615. /**
  28616. * Sets the mesh VertexBuffer.
  28617. * Returns the Mesh.
  28618. */
  28619. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28620. if (!this._geometry) {
  28621. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28622. }
  28623. this._geometry.setVerticesBuffer(buffer);
  28624. return this;
  28625. };
  28626. /**
  28627. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28628. * If the mesh has no geometry, it is simply returned as it is.
  28629. * The `data` are either a numeric array either a Float32Array.
  28630. * No new underlying VertexBuffer object is created.
  28631. * 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.
  28632. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28633. *
  28634. * Possible `kind` values :
  28635. * - BABYLON.VertexBuffer.PositionKind
  28636. * - BABYLON.VertexBuffer.UVKind
  28637. * - BABYLON.VertexBuffer.UV2Kind
  28638. * - BABYLON.VertexBuffer.UV3Kind
  28639. * - BABYLON.VertexBuffer.UV4Kind
  28640. * - BABYLON.VertexBuffer.UV5Kind
  28641. * - BABYLON.VertexBuffer.UV6Kind
  28642. * - BABYLON.VertexBuffer.ColorKind
  28643. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28644. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28645. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28646. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28647. *
  28648. * Returns the Mesh.
  28649. */
  28650. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28651. if (!this._geometry) {
  28652. return this;
  28653. }
  28654. if (!makeItUnique) {
  28655. this._geometry.updateVerticesData(kind, data, updateExtends);
  28656. }
  28657. else {
  28658. this.makeGeometryUnique();
  28659. this.updateVerticesData(kind, data, updateExtends, false);
  28660. }
  28661. return this;
  28662. };
  28663. /**
  28664. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28665. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28666. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28667. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28668. * Returns the Mesh.
  28669. */
  28670. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28671. if (computeNormals === void 0) { computeNormals = true; }
  28672. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28673. if (!positions) {
  28674. return this;
  28675. }
  28676. positionFunction(positions);
  28677. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28678. if (computeNormals) {
  28679. var indices = this.getIndices();
  28680. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28681. if (!normals) {
  28682. return this;
  28683. }
  28684. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28685. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28686. }
  28687. return this;
  28688. };
  28689. /**
  28690. * Creates a un-shared specific occurence of the geometry for the mesh.
  28691. * Returns the Mesh.
  28692. */
  28693. Mesh.prototype.makeGeometryUnique = function () {
  28694. if (!this._geometry) {
  28695. return this;
  28696. }
  28697. var oldGeometry = this._geometry;
  28698. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28699. oldGeometry.releaseForMesh(this, true);
  28700. geometry.applyToMesh(this);
  28701. return this;
  28702. };
  28703. /**
  28704. * Sets the mesh indices.
  28705. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28706. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28707. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28708. * This method creates a new index buffer each call.
  28709. * Returns the Mesh.
  28710. */
  28711. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28712. if (totalVertices === void 0) { totalVertices = null; }
  28713. if (updatable === void 0) { updatable = false; }
  28714. if (!this._geometry) {
  28715. var vertexData = new BABYLON.VertexData();
  28716. vertexData.indices = indices;
  28717. var scene = this.getScene();
  28718. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28719. }
  28720. else {
  28721. this._geometry.setIndices(indices, totalVertices, updatable);
  28722. }
  28723. return this;
  28724. };
  28725. /**
  28726. * Update the current index buffer
  28727. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28728. * Returns the Mesh.
  28729. */
  28730. Mesh.prototype.updateIndices = function (indices, offset) {
  28731. if (!this._geometry) {
  28732. return this;
  28733. }
  28734. this._geometry.updateIndices(indices, offset);
  28735. return this;
  28736. };
  28737. /**
  28738. * Invert the geometry to move from a right handed system to a left handed one.
  28739. * Returns the Mesh.
  28740. */
  28741. Mesh.prototype.toLeftHanded = function () {
  28742. if (!this._geometry) {
  28743. return this;
  28744. }
  28745. this._geometry.toLeftHanded();
  28746. return this;
  28747. };
  28748. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28749. if (!this._geometry) {
  28750. return this;
  28751. }
  28752. var engine = this.getScene().getEngine();
  28753. // Wireframe
  28754. var indexToBind;
  28755. if (this._unIndexed) {
  28756. indexToBind = null;
  28757. }
  28758. else {
  28759. switch (fillMode) {
  28760. case BABYLON.Material.PointFillMode:
  28761. indexToBind = null;
  28762. break;
  28763. case BABYLON.Material.WireFrameFillMode:
  28764. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28765. break;
  28766. default:
  28767. case BABYLON.Material.TriangleFillMode:
  28768. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28769. break;
  28770. }
  28771. }
  28772. // VBOs
  28773. this._geometry._bind(effect, indexToBind);
  28774. return this;
  28775. };
  28776. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28777. if (alternate === void 0) { alternate = false; }
  28778. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28779. return this;
  28780. }
  28781. this.onBeforeDrawObservable.notifyObservers(this);
  28782. var scene = this.getScene();
  28783. var engine = scene.getEngine();
  28784. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28785. // or triangles as points
  28786. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28787. }
  28788. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28789. // Triangles as wireframe
  28790. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28791. }
  28792. else {
  28793. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28794. }
  28795. if (scene._isAlternateRenderingEnabled && !alternate) {
  28796. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28797. if (!effect || !scene.activeCamera) {
  28798. return this;
  28799. }
  28800. scene._switchToAlternateCameraConfiguration(true);
  28801. this._effectiveMaterial.bindView(effect);
  28802. this._effectiveMaterial.bindViewProjection(effect);
  28803. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28804. this._draw(subMesh, fillMode, instancesCount, true);
  28805. engine.setViewport(scene.activeCamera.viewport);
  28806. scene._switchToAlternateCameraConfiguration(false);
  28807. this._effectiveMaterial.bindView(effect);
  28808. this._effectiveMaterial.bindViewProjection(effect);
  28809. }
  28810. return this;
  28811. };
  28812. /**
  28813. * Registers for this mesh a javascript function called just before the rendering process.
  28814. * This function is passed the current mesh.
  28815. * Return the Mesh.
  28816. */
  28817. Mesh.prototype.registerBeforeRender = function (func) {
  28818. this.onBeforeRenderObservable.add(func);
  28819. return this;
  28820. };
  28821. /**
  28822. * Disposes a previously registered javascript function called before the rendering.
  28823. * This function is passed the current mesh.
  28824. * Returns the Mesh.
  28825. */
  28826. Mesh.prototype.unregisterBeforeRender = function (func) {
  28827. this.onBeforeRenderObservable.removeCallback(func);
  28828. return this;
  28829. };
  28830. /**
  28831. * Registers for this mesh a javascript function called just after the rendering is complete.
  28832. * This function is passed the current mesh.
  28833. * Returns the Mesh.
  28834. */
  28835. Mesh.prototype.registerAfterRender = function (func) {
  28836. this.onAfterRenderObservable.add(func);
  28837. return this;
  28838. };
  28839. /**
  28840. * Disposes a previously registered javascript function called after the rendering.
  28841. * This function is passed the current mesh.
  28842. * Return the Mesh.
  28843. */
  28844. Mesh.prototype.unregisterAfterRender = function (func) {
  28845. this.onAfterRenderObservable.removeCallback(func);
  28846. return this;
  28847. };
  28848. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28849. var scene = this.getScene();
  28850. this._batchCache.mustReturn = false;
  28851. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28852. this._batchCache.visibleInstances[subMeshId] = null;
  28853. if (this._visibleInstances) {
  28854. var currentRenderId = scene.getRenderId();
  28855. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28856. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28857. var selfRenderId = this._renderId;
  28858. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28859. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28860. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28861. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28862. }
  28863. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28864. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28865. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28866. this._batchCache.mustReturn = true;
  28867. return this._batchCache;
  28868. }
  28869. if (currentRenderId !== selfRenderId) {
  28870. this._batchCache.renderSelf[subMeshId] = false;
  28871. }
  28872. }
  28873. this._renderIdForInstances[subMeshId] = currentRenderId;
  28874. }
  28875. return this._batchCache;
  28876. };
  28877. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28878. var visibleInstances = batch.visibleInstances[subMesh._id];
  28879. if (!visibleInstances) {
  28880. return this;
  28881. }
  28882. var matricesCount = visibleInstances.length + 1;
  28883. var bufferSize = matricesCount * 16 * 4;
  28884. var currentInstancesBufferSize = this._instancesBufferSize;
  28885. var instancesBuffer = this._instancesBuffer;
  28886. while (this._instancesBufferSize < bufferSize) {
  28887. this._instancesBufferSize *= 2;
  28888. }
  28889. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28890. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28891. }
  28892. var offset = 0;
  28893. var instancesCount = 0;
  28894. var world = this.getWorldMatrix();
  28895. if (batch.renderSelf[subMesh._id]) {
  28896. world.copyToArray(this._instancesData, offset);
  28897. offset += 16;
  28898. instancesCount++;
  28899. }
  28900. if (visibleInstances) {
  28901. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28902. var instance = visibleInstances[instanceIndex];
  28903. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28904. offset += 16;
  28905. instancesCount++;
  28906. }
  28907. }
  28908. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28909. if (instancesBuffer) {
  28910. instancesBuffer.dispose();
  28911. }
  28912. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28913. this._instancesBuffer = instancesBuffer;
  28914. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28915. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28916. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28917. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28918. }
  28919. else {
  28920. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28921. }
  28922. this._bind(subMesh, effect, fillMode);
  28923. this._draw(subMesh, fillMode, instancesCount);
  28924. engine.unbindInstanceAttributes();
  28925. return this;
  28926. };
  28927. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28928. var scene = this.getScene();
  28929. var engine = scene.getEngine();
  28930. if (hardwareInstancedRendering) {
  28931. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28932. }
  28933. else {
  28934. if (batch.renderSelf[subMesh._id]) {
  28935. // Draw
  28936. if (onBeforeDraw) {
  28937. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28938. }
  28939. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28940. }
  28941. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28942. if (visibleInstancesForSubMesh) {
  28943. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28944. var instance = visibleInstancesForSubMesh[instanceIndex];
  28945. // World
  28946. var world = instance.getWorldMatrix();
  28947. if (onBeforeDraw) {
  28948. onBeforeDraw(true, world, effectiveMaterial);
  28949. }
  28950. // Draw
  28951. this._draw(subMesh, fillMode);
  28952. }
  28953. }
  28954. }
  28955. return this;
  28956. };
  28957. /**
  28958. * Triggers the draw call for the mesh.
  28959. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28960. * Returns the Mesh.
  28961. */
  28962. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28963. this.checkOcclusionQuery();
  28964. if (this._isOccluded) {
  28965. return this;
  28966. }
  28967. var scene = this.getScene();
  28968. // Managing instances
  28969. var batch = this._getInstancesRenderList(subMesh._id);
  28970. if (batch.mustReturn) {
  28971. return this;
  28972. }
  28973. // Checking geometry state
  28974. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28975. return this;
  28976. }
  28977. this.onBeforeRenderObservable.notifyObservers(this);
  28978. var engine = scene.getEngine();
  28979. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28980. // Material
  28981. var material = subMesh.getMaterial();
  28982. if (!material) {
  28983. return this;
  28984. }
  28985. this._effectiveMaterial = material;
  28986. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28987. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28988. return this;
  28989. }
  28990. }
  28991. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28992. return this;
  28993. }
  28994. // Alpha mode
  28995. if (enableAlphaMode) {
  28996. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28997. }
  28998. // Outline - step 1
  28999. var savedDepthWrite = engine.getDepthWrite();
  29000. if (this.renderOutline) {
  29001. engine.setDepthWrite(false);
  29002. scene.getOutlineRenderer().render(subMesh, batch);
  29003. engine.setDepthWrite(savedDepthWrite);
  29004. }
  29005. var effect;
  29006. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29007. effect = subMesh.effect;
  29008. }
  29009. else {
  29010. effect = this._effectiveMaterial.getEffect();
  29011. }
  29012. if (!effect) {
  29013. return this;
  29014. }
  29015. var sideOrientation = this.overrideMaterialSideOrientation;
  29016. if (sideOrientation == null) {
  29017. sideOrientation = this._effectiveMaterial.sideOrientation;
  29018. if (this._getWorldMatrixDeterminant() < 0) {
  29019. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29020. }
  29021. }
  29022. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29023. if (this._effectiveMaterial.forceDepthWrite) {
  29024. engine.setDepthWrite(true);
  29025. }
  29026. // Bind
  29027. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29028. if (!hardwareInstancedRendering) {
  29029. this._bind(subMesh, effect, fillMode);
  29030. }
  29031. var world = this.getWorldMatrix();
  29032. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29033. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29034. }
  29035. else {
  29036. this._effectiveMaterial.bind(world, this);
  29037. }
  29038. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29039. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29040. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29041. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29042. }
  29043. // Draw
  29044. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29045. // Unbind
  29046. this._effectiveMaterial.unbind();
  29047. // Outline - step 2
  29048. if (this.renderOutline && savedDepthWrite) {
  29049. engine.setDepthWrite(true);
  29050. engine.setColorWrite(false);
  29051. scene.getOutlineRenderer().render(subMesh, batch);
  29052. engine.setColorWrite(true);
  29053. }
  29054. // Overlay
  29055. if (this.renderOverlay) {
  29056. var currentMode = engine.getAlphaMode();
  29057. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29058. scene.getOutlineRenderer().render(subMesh, batch, true);
  29059. engine.setAlphaMode(currentMode);
  29060. }
  29061. this.onAfterRenderObservable.notifyObservers(this);
  29062. return this;
  29063. };
  29064. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29065. if (isInstance && effectiveMaterial) {
  29066. effectiveMaterial.bindOnlyWorldMatrix(world);
  29067. }
  29068. };
  29069. /**
  29070. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29071. */
  29072. Mesh.prototype.getEmittedParticleSystems = function () {
  29073. var results = new Array();
  29074. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29075. var particleSystem = this.getScene().particleSystems[index];
  29076. if (particleSystem.emitter === this) {
  29077. results.push(particleSystem);
  29078. }
  29079. }
  29080. return results;
  29081. };
  29082. /**
  29083. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29084. */
  29085. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29086. var results = new Array();
  29087. var descendants = this.getDescendants();
  29088. descendants.push(this);
  29089. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29090. var particleSystem = this.getScene().particleSystems[index];
  29091. var emitter = particleSystem.emitter;
  29092. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29093. results.push(particleSystem);
  29094. }
  29095. }
  29096. return results;
  29097. };
  29098. Mesh.prototype._checkDelayState = function () {
  29099. var scene = this.getScene();
  29100. if (this._geometry) {
  29101. this._geometry.load(scene);
  29102. }
  29103. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29104. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29105. this._queueLoad(scene);
  29106. }
  29107. return this;
  29108. };
  29109. Mesh.prototype._queueLoad = function (scene) {
  29110. var _this = this;
  29111. scene._addPendingData(this);
  29112. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29113. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29114. if (data instanceof ArrayBuffer) {
  29115. _this._delayLoadingFunction(data, _this);
  29116. }
  29117. else {
  29118. _this._delayLoadingFunction(JSON.parse(data), _this);
  29119. }
  29120. _this.instances.forEach(function (instance) {
  29121. instance._syncSubMeshes();
  29122. });
  29123. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29124. scene._removePendingData(_this);
  29125. }, function () { }, scene.database, getBinaryData);
  29126. return this;
  29127. };
  29128. /**
  29129. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29130. */
  29131. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29132. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29133. return false;
  29134. }
  29135. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29136. return false;
  29137. }
  29138. this._checkDelayState();
  29139. return true;
  29140. };
  29141. /**
  29142. * Sets the mesh material by the material or multiMaterial `id` property.
  29143. * The material `id` is a string identifying the material or the multiMaterial.
  29144. * This method returns the Mesh.
  29145. */
  29146. Mesh.prototype.setMaterialByID = function (id) {
  29147. var materials = this.getScene().materials;
  29148. var index;
  29149. for (index = materials.length - 1; index > -1; index--) {
  29150. if (materials[index].id === id) {
  29151. this.material = materials[index];
  29152. return this;
  29153. }
  29154. }
  29155. // Multi
  29156. var multiMaterials = this.getScene().multiMaterials;
  29157. for (index = multiMaterials.length - 1; index > -1; index--) {
  29158. if (multiMaterials[index].id === id) {
  29159. this.material = multiMaterials[index];
  29160. return this;
  29161. }
  29162. }
  29163. return this;
  29164. };
  29165. /**
  29166. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29167. */
  29168. Mesh.prototype.getAnimatables = function () {
  29169. var results = new Array();
  29170. if (this.material) {
  29171. results.push(this.material);
  29172. }
  29173. if (this.skeleton) {
  29174. results.push(this.skeleton);
  29175. }
  29176. return results;
  29177. };
  29178. /**
  29179. * Modifies the mesh geometry according to the passed transformation matrix.
  29180. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29181. * The mesh normals are modified accordingly the same transformation.
  29182. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29183. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29184. * Returns the Mesh.
  29185. */
  29186. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29187. // Position
  29188. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29189. return this;
  29190. }
  29191. var submeshes = this.subMeshes.splice(0);
  29192. this._resetPointsArrayCache();
  29193. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29194. var temp = new Array();
  29195. var index;
  29196. for (index = 0; index < data.length; index += 3) {
  29197. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29198. }
  29199. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29200. // Normals
  29201. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29202. return this;
  29203. }
  29204. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29205. temp = [];
  29206. for (index = 0; index < data.length; index += 3) {
  29207. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29208. }
  29209. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29210. // flip faces?
  29211. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29212. this.flipFaces();
  29213. }
  29214. // Restore submeshes
  29215. this.releaseSubMeshes();
  29216. this.subMeshes = submeshes;
  29217. return this;
  29218. };
  29219. /**
  29220. * Modifies the mesh geometry according to its own current World Matrix.
  29221. * The mesh World Matrix is then reset.
  29222. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29223. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29224. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29225. * Returns the Mesh.
  29226. */
  29227. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29228. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29229. this.scaling.copyFromFloats(1, 1, 1);
  29230. this.position.copyFromFloats(0, 0, 0);
  29231. this.rotation.copyFromFloats(0, 0, 0);
  29232. //only if quaternion is already set
  29233. if (this.rotationQuaternion) {
  29234. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29235. }
  29236. this._worldMatrix = BABYLON.Matrix.Identity();
  29237. return this;
  29238. };
  29239. Object.defineProperty(Mesh.prototype, "_positions", {
  29240. // Cache
  29241. get: function () {
  29242. if (this._geometry) {
  29243. return this._geometry._positions;
  29244. }
  29245. return null;
  29246. },
  29247. enumerable: true,
  29248. configurable: true
  29249. });
  29250. Mesh.prototype._resetPointsArrayCache = function () {
  29251. if (this._geometry) {
  29252. this._geometry._resetPointsArrayCache();
  29253. }
  29254. return this;
  29255. };
  29256. Mesh.prototype._generatePointsArray = function () {
  29257. if (this._geometry) {
  29258. return this._geometry._generatePointsArray();
  29259. }
  29260. return false;
  29261. };
  29262. /**
  29263. * Returns a new Mesh object generated from the current mesh properties.
  29264. * This method must not get confused with createInstance().
  29265. * The parameter `name` is a string, the name given to the new mesh.
  29266. * The optional parameter `newParent` can be any Node object (default `null`).
  29267. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29268. * 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.
  29269. */
  29270. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29271. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29272. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29273. };
  29274. /**
  29275. * Releases resources associated with this mesh.
  29276. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29277. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29278. */
  29279. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29280. var _this = this;
  29281. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29282. this.morphTargetManager = null;
  29283. if (this._geometry) {
  29284. this._geometry.releaseForMesh(this, true);
  29285. }
  29286. // Sources
  29287. var meshes = this.getScene().meshes;
  29288. meshes.forEach(function (abstractMesh) {
  29289. var mesh = abstractMesh;
  29290. if (mesh._source && mesh._source === _this) {
  29291. mesh._source = null;
  29292. }
  29293. });
  29294. this._source = null;
  29295. // Instances
  29296. if (this._instancesBuffer) {
  29297. this._instancesBuffer.dispose();
  29298. this._instancesBuffer = null;
  29299. }
  29300. while (this.instances.length) {
  29301. this.instances[0].dispose();
  29302. }
  29303. // Effect layers.
  29304. var effectLayers = this.getScene().effectLayers;
  29305. for (var i = 0; i < effectLayers.length; i++) {
  29306. var effectLayer = effectLayers[i];
  29307. if (effectLayer) {
  29308. effectLayer._disposeMesh(this);
  29309. }
  29310. }
  29311. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29312. };
  29313. /**
  29314. * Modifies the mesh geometry according to a displacement map.
  29315. * 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.
  29316. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29317. * This method returns nothing.
  29318. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29319. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29320. * 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.
  29321. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29322. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29323. *
  29324. * Returns the Mesh.
  29325. */
  29326. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29327. var _this = this;
  29328. var scene = this.getScene();
  29329. var onload = function (img) {
  29330. // Getting height map data
  29331. var canvas = document.createElement("canvas");
  29332. var context = canvas.getContext("2d");
  29333. var heightMapWidth = img.width;
  29334. var heightMapHeight = img.height;
  29335. canvas.width = heightMapWidth;
  29336. canvas.height = heightMapHeight;
  29337. context.drawImage(img, 0, 0);
  29338. // Create VertexData from map data
  29339. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29340. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29341. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29342. //execute success callback, if set
  29343. if (onSuccess) {
  29344. onSuccess(_this);
  29345. }
  29346. };
  29347. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29348. return this;
  29349. };
  29350. /**
  29351. * Modifies the mesh geometry according to a displacementMap buffer.
  29352. * 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.
  29353. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29354. * This method returns nothing.
  29355. * 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.
  29356. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29357. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29358. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29359. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29360. *
  29361. * Returns the Mesh.
  29362. */
  29363. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29364. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29365. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29366. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29367. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29368. return this;
  29369. }
  29370. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29371. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29372. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29373. var position = BABYLON.Vector3.Zero();
  29374. var normal = BABYLON.Vector3.Zero();
  29375. var uv = BABYLON.Vector2.Zero();
  29376. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29377. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29378. for (var index = 0; index < positions.length; index += 3) {
  29379. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29380. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29381. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29382. // Compute height
  29383. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29384. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29385. var pos = (u + v * heightMapWidth) * 4;
  29386. var r = buffer[pos] / 255.0;
  29387. var g = buffer[pos + 1] / 255.0;
  29388. var b = buffer[pos + 2] / 255.0;
  29389. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29390. normal.normalize();
  29391. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29392. position = position.add(normal);
  29393. position.toArray(positions, index);
  29394. }
  29395. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29396. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29397. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29398. return this;
  29399. };
  29400. /**
  29401. * Modify the mesh to get a flat shading rendering.
  29402. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29403. * This method returns the Mesh.
  29404. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29405. */
  29406. Mesh.prototype.convertToFlatShadedMesh = function () {
  29407. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29408. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29409. var kinds = this.getVerticesDataKinds();
  29410. var vbs = {};
  29411. var data = {};
  29412. var newdata = {};
  29413. var updatableNormals = false;
  29414. var kindIndex;
  29415. var kind;
  29416. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29417. kind = kinds[kindIndex];
  29418. var vertexBuffer = this.getVertexBuffer(kind);
  29419. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29420. updatableNormals = vertexBuffer.isUpdatable();
  29421. kinds.splice(kindIndex, 1);
  29422. kindIndex--;
  29423. continue;
  29424. }
  29425. vbs[kind] = vertexBuffer;
  29426. data[kind] = vbs[kind].getData();
  29427. newdata[kind] = [];
  29428. }
  29429. // Save previous submeshes
  29430. var previousSubmeshes = this.subMeshes.slice(0);
  29431. var indices = this.getIndices();
  29432. var totalIndices = this.getTotalIndices();
  29433. // Generating unique vertices per face
  29434. var index;
  29435. for (index = 0; index < totalIndices; index++) {
  29436. var vertexIndex = indices[index];
  29437. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29438. kind = kinds[kindIndex];
  29439. var stride = vbs[kind].getStrideSize();
  29440. for (var offset = 0; offset < stride; offset++) {
  29441. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29442. }
  29443. }
  29444. }
  29445. // Updating faces & normal
  29446. var normals = [];
  29447. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29448. for (index = 0; index < totalIndices; index += 3) {
  29449. indices[index] = index;
  29450. indices[index + 1] = index + 1;
  29451. indices[index + 2] = index + 2;
  29452. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29453. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29454. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29455. var p1p2 = p1.subtract(p2);
  29456. var p3p2 = p3.subtract(p2);
  29457. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29458. // Store same normals for every vertex
  29459. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29460. normals.push(normal.x);
  29461. normals.push(normal.y);
  29462. normals.push(normal.z);
  29463. }
  29464. }
  29465. this.setIndices(indices);
  29466. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29467. // Updating vertex buffers
  29468. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29469. kind = kinds[kindIndex];
  29470. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29471. }
  29472. // Updating submeshes
  29473. this.releaseSubMeshes();
  29474. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29475. var previousOne = previousSubmeshes[submeshIndex];
  29476. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29477. }
  29478. this.synchronizeInstances();
  29479. return this;
  29480. };
  29481. /**
  29482. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29483. * In other words, more vertices, no more indices and a single bigger VBO.
  29484. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29485. * Returns the Mesh.
  29486. */
  29487. Mesh.prototype.convertToUnIndexedMesh = function () {
  29488. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29489. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29490. var kinds = this.getVerticesDataKinds();
  29491. var vbs = {};
  29492. var data = {};
  29493. var newdata = {};
  29494. var kindIndex;
  29495. var kind;
  29496. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29497. kind = kinds[kindIndex];
  29498. var vertexBuffer = this.getVertexBuffer(kind);
  29499. vbs[kind] = vertexBuffer;
  29500. data[kind] = vbs[kind].getData();
  29501. newdata[kind] = [];
  29502. }
  29503. // Save previous submeshes
  29504. var previousSubmeshes = this.subMeshes.slice(0);
  29505. var indices = this.getIndices();
  29506. var totalIndices = this.getTotalIndices();
  29507. // Generating unique vertices per face
  29508. var index;
  29509. for (index = 0; index < totalIndices; index++) {
  29510. var vertexIndex = indices[index];
  29511. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29512. kind = kinds[kindIndex];
  29513. var stride = vbs[kind].getStrideSize();
  29514. for (var offset = 0; offset < stride; offset++) {
  29515. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29516. }
  29517. }
  29518. }
  29519. // Updating indices
  29520. for (index = 0; index < totalIndices; index += 3) {
  29521. indices[index] = index;
  29522. indices[index + 1] = index + 1;
  29523. indices[index + 2] = index + 2;
  29524. }
  29525. this.setIndices(indices);
  29526. // Updating vertex buffers
  29527. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29528. kind = kinds[kindIndex];
  29529. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29530. }
  29531. // Updating submeshes
  29532. this.releaseSubMeshes();
  29533. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29534. var previousOne = previousSubmeshes[submeshIndex];
  29535. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29536. }
  29537. this._unIndexed = true;
  29538. this.synchronizeInstances();
  29539. return this;
  29540. };
  29541. /**
  29542. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29543. * This method returns the Mesh.
  29544. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29545. */
  29546. Mesh.prototype.flipFaces = function (flipNormals) {
  29547. if (flipNormals === void 0) { flipNormals = false; }
  29548. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29549. var i;
  29550. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29551. for (i = 0; i < vertex_data.normals.length; i++) {
  29552. vertex_data.normals[i] *= -1;
  29553. }
  29554. }
  29555. if (vertex_data.indices) {
  29556. var temp;
  29557. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29558. // reassign indices
  29559. temp = vertex_data.indices[i + 1];
  29560. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29561. vertex_data.indices[i + 2] = temp;
  29562. }
  29563. }
  29564. vertex_data.applyToMesh(this);
  29565. return this;
  29566. };
  29567. // Instances
  29568. /**
  29569. * Creates a new InstancedMesh object from the mesh model.
  29570. * An instance shares the same properties and the same material than its model.
  29571. * Only these properties of each instance can then be set individually :
  29572. * - position
  29573. * - rotation
  29574. * - rotationQuaternion
  29575. * - setPivotMatrix
  29576. * - scaling
  29577. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29578. * Warning : this method is not supported for Line mesh and LineSystem
  29579. */
  29580. Mesh.prototype.createInstance = function (name) {
  29581. return new BABYLON.InstancedMesh(name, this);
  29582. };
  29583. /**
  29584. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29585. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29586. * This method returns the Mesh.
  29587. */
  29588. Mesh.prototype.synchronizeInstances = function () {
  29589. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29590. var instance = this.instances[instanceIndex];
  29591. instance._syncSubMeshes();
  29592. }
  29593. return this;
  29594. };
  29595. /**
  29596. * Simplify the mesh according to the given array of settings.
  29597. * Function will return immediately and will simplify async. It returns the Mesh.
  29598. * @param settings a collection of simplification settings.
  29599. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29600. * @param type the type of simplification to run.
  29601. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29602. */
  29603. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29604. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29605. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29606. this.getScene().simplificationQueue.addTask({
  29607. settings: settings,
  29608. parallelProcessing: parallelProcessing,
  29609. mesh: this,
  29610. simplificationType: simplificationType,
  29611. successCallback: successCallback
  29612. });
  29613. return this;
  29614. };
  29615. /**
  29616. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29617. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29618. * This should be used together with the simplification to avoid disappearing triangles.
  29619. * Returns the Mesh.
  29620. * @param successCallback an optional success callback to be called after the optimization finished.
  29621. */
  29622. Mesh.prototype.optimizeIndices = function (successCallback) {
  29623. var _this = this;
  29624. var indices = this.getIndices();
  29625. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29626. if (!positions || !indices) {
  29627. return this;
  29628. }
  29629. var vectorPositions = new Array();
  29630. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29631. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29632. }
  29633. var dupes = new Array();
  29634. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29635. var realPos = vectorPositions.length - 1 - iteration;
  29636. var testedPosition = vectorPositions[realPos];
  29637. for (var j = 0; j < realPos; ++j) {
  29638. var againstPosition = vectorPositions[j];
  29639. if (testedPosition.equals(againstPosition)) {
  29640. dupes[realPos] = j;
  29641. break;
  29642. }
  29643. }
  29644. }, function () {
  29645. for (var i = 0; i < indices.length; ++i) {
  29646. indices[i] = dupes[indices[i]] || indices[i];
  29647. }
  29648. //indices are now reordered
  29649. var originalSubMeshes = _this.subMeshes.slice(0);
  29650. _this.setIndices(indices);
  29651. _this.subMeshes = originalSubMeshes;
  29652. if (successCallback) {
  29653. successCallback(_this);
  29654. }
  29655. });
  29656. return this;
  29657. };
  29658. Mesh.prototype.serialize = function (serializationObject) {
  29659. serializationObject.name = this.name;
  29660. serializationObject.id = this.id;
  29661. serializationObject.type = this.getClassName();
  29662. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29663. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29664. }
  29665. serializationObject.position = this.position.asArray();
  29666. if (this.rotationQuaternion) {
  29667. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29668. }
  29669. else if (this.rotation) {
  29670. serializationObject.rotation = this.rotation.asArray();
  29671. }
  29672. serializationObject.scaling = this.scaling.asArray();
  29673. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29674. serializationObject.isEnabled = this.isEnabled(false);
  29675. serializationObject.isVisible = this.isVisible;
  29676. serializationObject.infiniteDistance = this.infiniteDistance;
  29677. serializationObject.pickable = this.isPickable;
  29678. serializationObject.receiveShadows = this.receiveShadows;
  29679. serializationObject.billboardMode = this.billboardMode;
  29680. serializationObject.visibility = this.visibility;
  29681. serializationObject.checkCollisions = this.checkCollisions;
  29682. serializationObject.isBlocker = this.isBlocker;
  29683. // Parent
  29684. if (this.parent) {
  29685. serializationObject.parentId = this.parent.id;
  29686. }
  29687. // Geometry
  29688. serializationObject.isUnIndexed = this.isUnIndexed;
  29689. var geometry = this._geometry;
  29690. if (geometry) {
  29691. var geometryId = geometry.id;
  29692. serializationObject.geometryId = geometryId;
  29693. // SubMeshes
  29694. serializationObject.subMeshes = [];
  29695. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29696. var subMesh = this.subMeshes[subIndex];
  29697. serializationObject.subMeshes.push({
  29698. materialIndex: subMesh.materialIndex,
  29699. verticesStart: subMesh.verticesStart,
  29700. verticesCount: subMesh.verticesCount,
  29701. indexStart: subMesh.indexStart,
  29702. indexCount: subMesh.indexCount
  29703. });
  29704. }
  29705. }
  29706. // Material
  29707. if (this.material) {
  29708. serializationObject.materialId = this.material.id;
  29709. }
  29710. else {
  29711. this.material = null;
  29712. }
  29713. // Morph targets
  29714. if (this.morphTargetManager) {
  29715. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29716. }
  29717. // Skeleton
  29718. if (this.skeleton) {
  29719. serializationObject.skeletonId = this.skeleton.id;
  29720. }
  29721. // Physics
  29722. //TODO implement correct serialization for physics impostors.
  29723. var impostor = this.getPhysicsImpostor();
  29724. if (impostor) {
  29725. serializationObject.physicsMass = impostor.getParam("mass");
  29726. serializationObject.physicsFriction = impostor.getParam("friction");
  29727. serializationObject.physicsRestitution = impostor.getParam("mass");
  29728. serializationObject.physicsImpostor = impostor.type;
  29729. }
  29730. // Metadata
  29731. if (this.metadata) {
  29732. serializationObject.metadata = this.metadata;
  29733. }
  29734. // Instances
  29735. serializationObject.instances = [];
  29736. for (var index = 0; index < this.instances.length; index++) {
  29737. var instance = this.instances[index];
  29738. var serializationInstance = {
  29739. name: instance.name,
  29740. id: instance.id,
  29741. position: instance.position.asArray(),
  29742. scaling: instance.scaling.asArray()
  29743. };
  29744. if (instance.rotationQuaternion) {
  29745. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29746. }
  29747. else if (instance.rotation) {
  29748. serializationInstance.rotation = instance.rotation.asArray();
  29749. }
  29750. serializationObject.instances.push(serializationInstance);
  29751. // Animations
  29752. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29753. serializationInstance.ranges = instance.serializeAnimationRanges();
  29754. }
  29755. //
  29756. // Animations
  29757. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29758. serializationObject.ranges = this.serializeAnimationRanges();
  29759. // Layer mask
  29760. serializationObject.layerMask = this.layerMask;
  29761. // Alpha
  29762. serializationObject.alphaIndex = this.alphaIndex;
  29763. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29764. // Overlay
  29765. serializationObject.overlayAlpha = this.overlayAlpha;
  29766. serializationObject.overlayColor = this.overlayColor.asArray();
  29767. serializationObject.renderOverlay = this.renderOverlay;
  29768. // Fog
  29769. serializationObject.applyFog = this.applyFog;
  29770. // Action Manager
  29771. if (this.actionManager) {
  29772. serializationObject.actions = this.actionManager.serialize(this.name);
  29773. }
  29774. };
  29775. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29776. if (!this.geometry) {
  29777. return;
  29778. }
  29779. this._markSubMeshesAsAttributesDirty();
  29780. var morphTargetManager = this._morphTargetManager;
  29781. if (morphTargetManager && morphTargetManager.vertexCount) {
  29782. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29783. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29784. this.morphTargetManager = null;
  29785. return;
  29786. }
  29787. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29788. var morphTarget = morphTargetManager.getActiveTarget(index);
  29789. var positions = morphTarget.getPositions();
  29790. if (!positions) {
  29791. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29792. return;
  29793. }
  29794. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29795. var normals = morphTarget.getNormals();
  29796. if (normals) {
  29797. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29798. }
  29799. var tangents = morphTarget.getTangents();
  29800. if (tangents) {
  29801. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29802. }
  29803. }
  29804. }
  29805. else {
  29806. var index = 0;
  29807. // Positions
  29808. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29809. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29810. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29811. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29812. }
  29813. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29814. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29815. }
  29816. index++;
  29817. }
  29818. }
  29819. };
  29820. // Statics
  29821. /**
  29822. * Returns a new Mesh object parsed from the source provided.
  29823. * The parameter `parsedMesh` is the source.
  29824. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29825. */
  29826. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29827. var mesh;
  29828. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29829. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29830. }
  29831. else {
  29832. mesh = new Mesh(parsedMesh.name, scene);
  29833. }
  29834. mesh.id = parsedMesh.id;
  29835. if (BABYLON.Tags) {
  29836. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29837. }
  29838. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29839. if (parsedMesh.metadata !== undefined) {
  29840. mesh.metadata = parsedMesh.metadata;
  29841. }
  29842. if (parsedMesh.rotationQuaternion) {
  29843. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29844. }
  29845. else if (parsedMesh.rotation) {
  29846. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29847. }
  29848. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29849. if (parsedMesh.localMatrix) {
  29850. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29851. }
  29852. else if (parsedMesh.pivotMatrix) {
  29853. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29854. }
  29855. mesh.setEnabled(parsedMesh.isEnabled);
  29856. mesh.isVisible = parsedMesh.isVisible;
  29857. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29858. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29859. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29860. if (parsedMesh.applyFog !== undefined) {
  29861. mesh.applyFog = parsedMesh.applyFog;
  29862. }
  29863. if (parsedMesh.pickable !== undefined) {
  29864. mesh.isPickable = parsedMesh.pickable;
  29865. }
  29866. if (parsedMesh.alphaIndex !== undefined) {
  29867. mesh.alphaIndex = parsedMesh.alphaIndex;
  29868. }
  29869. mesh.receiveShadows = parsedMesh.receiveShadows;
  29870. mesh.billboardMode = parsedMesh.billboardMode;
  29871. if (parsedMesh.visibility !== undefined) {
  29872. mesh.visibility = parsedMesh.visibility;
  29873. }
  29874. mesh.checkCollisions = parsedMesh.checkCollisions;
  29875. if (parsedMesh.isBlocker !== undefined) {
  29876. mesh.isBlocker = parsedMesh.isBlocker;
  29877. }
  29878. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29879. // freezeWorldMatrix
  29880. if (parsedMesh.freezeWorldMatrix) {
  29881. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29882. }
  29883. // Parent
  29884. if (parsedMesh.parentId) {
  29885. mesh._waitingParentId = parsedMesh.parentId;
  29886. }
  29887. // Actions
  29888. if (parsedMesh.actions !== undefined) {
  29889. mesh._waitingActions = parsedMesh.actions;
  29890. }
  29891. // Overlay
  29892. if (parsedMesh.overlayAlpha !== undefined) {
  29893. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29894. }
  29895. if (parsedMesh.overlayColor !== undefined) {
  29896. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29897. }
  29898. if (parsedMesh.renderOverlay !== undefined) {
  29899. mesh.renderOverlay = parsedMesh.renderOverlay;
  29900. }
  29901. // Geometry
  29902. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29903. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29904. if (parsedMesh.delayLoadingFile) {
  29905. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29906. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29907. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29908. if (parsedMesh._binaryInfo) {
  29909. mesh._binaryInfo = parsedMesh._binaryInfo;
  29910. }
  29911. mesh._delayInfo = [];
  29912. if (parsedMesh.hasUVs) {
  29913. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29914. }
  29915. if (parsedMesh.hasUVs2) {
  29916. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29917. }
  29918. if (parsedMesh.hasUVs3) {
  29919. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29920. }
  29921. if (parsedMesh.hasUVs4) {
  29922. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29923. }
  29924. if (parsedMesh.hasUVs5) {
  29925. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29926. }
  29927. if (parsedMesh.hasUVs6) {
  29928. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29929. }
  29930. if (parsedMesh.hasColors) {
  29931. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29932. }
  29933. if (parsedMesh.hasMatricesIndices) {
  29934. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29935. }
  29936. if (parsedMesh.hasMatricesWeights) {
  29937. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29938. }
  29939. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29940. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29941. mesh._checkDelayState();
  29942. }
  29943. }
  29944. else {
  29945. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29946. }
  29947. // Material
  29948. if (parsedMesh.materialId) {
  29949. mesh.setMaterialByID(parsedMesh.materialId);
  29950. }
  29951. else {
  29952. mesh.material = null;
  29953. }
  29954. // Morph targets
  29955. if (parsedMesh.morphTargetManagerId > -1) {
  29956. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29957. }
  29958. // Skeleton
  29959. if (parsedMesh.skeletonId > -1) {
  29960. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29961. if (parsedMesh.numBoneInfluencers) {
  29962. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29963. }
  29964. }
  29965. // Animations
  29966. if (parsedMesh.animations) {
  29967. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29968. var parsedAnimation = parsedMesh.animations[animationIndex];
  29969. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29970. }
  29971. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29972. }
  29973. if (parsedMesh.autoAnimate) {
  29974. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29975. }
  29976. // Layer Mask
  29977. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29978. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29979. }
  29980. else {
  29981. mesh.layerMask = 0x0FFFFFFF;
  29982. }
  29983. // Physics
  29984. if (parsedMesh.physicsImpostor) {
  29985. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29986. mass: parsedMesh.physicsMass,
  29987. friction: parsedMesh.physicsFriction,
  29988. restitution: parsedMesh.physicsRestitution
  29989. }, scene);
  29990. }
  29991. // Instances
  29992. if (parsedMesh.instances) {
  29993. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29994. var parsedInstance = parsedMesh.instances[index];
  29995. var instance = mesh.createInstance(parsedInstance.name);
  29996. if (parsedInstance.id) {
  29997. instance.id = parsedInstance.id;
  29998. }
  29999. if (BABYLON.Tags) {
  30000. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30001. }
  30002. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30003. if (parsedInstance.parentId) {
  30004. instance._waitingParentId = parsedInstance.parentId;
  30005. }
  30006. if (parsedInstance.rotationQuaternion) {
  30007. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30008. }
  30009. else if (parsedInstance.rotation) {
  30010. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30011. }
  30012. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30013. instance.checkCollisions = mesh.checkCollisions;
  30014. if (parsedMesh.animations) {
  30015. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30016. parsedAnimation = parsedMesh.animations[animationIndex];
  30017. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30018. }
  30019. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30020. }
  30021. }
  30022. }
  30023. return mesh;
  30024. };
  30025. /**
  30026. * Creates a ribbon mesh.
  30027. * Please consider using the same method from the MeshBuilder class instead.
  30028. * 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.
  30029. *
  30030. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30031. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30032. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30033. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30034. * 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.
  30035. * 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.
  30036. * 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
  30037. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30038. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30040. */
  30041. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30042. if (closeArray === void 0) { closeArray = false; }
  30043. if (updatable === void 0) { updatable = false; }
  30044. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30045. pathArray: pathArray,
  30046. closeArray: closeArray,
  30047. closePath: closePath,
  30048. offset: offset,
  30049. updatable: updatable,
  30050. sideOrientation: sideOrientation,
  30051. instance: instance
  30052. }, scene);
  30053. };
  30054. /**
  30055. * Creates a plane polygonal mesh. By default, this is a disc.
  30056. * Please consider using the same method from the MeshBuilder class instead.
  30057. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30058. * 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.
  30059. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30060. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30061. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30062. */
  30063. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30064. if (scene === void 0) { scene = null; }
  30065. var options = {
  30066. radius: radius,
  30067. tessellation: tessellation,
  30068. sideOrientation: sideOrientation,
  30069. updatable: updatable
  30070. };
  30071. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30072. };
  30073. /**
  30074. * Creates a box mesh.
  30075. * Please consider using the same method from the MeshBuilder class instead.
  30076. * The parameter `size` sets the size (float) of each box side (default 1).
  30077. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30078. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30079. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30080. */
  30081. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30082. if (scene === void 0) { scene = null; }
  30083. var options = {
  30084. size: size,
  30085. sideOrientation: sideOrientation,
  30086. updatable: updatable
  30087. };
  30088. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30089. };
  30090. /**
  30091. * Creates a sphere mesh.
  30092. * Please consider using the same method from the MeshBuilder class instead.
  30093. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30094. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30096. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30097. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30098. */
  30099. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30100. var options = {
  30101. segments: segments,
  30102. diameterX: diameter,
  30103. diameterY: diameter,
  30104. diameterZ: diameter,
  30105. sideOrientation: sideOrientation,
  30106. updatable: updatable
  30107. };
  30108. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30109. };
  30110. /**
  30111. * Creates a cylinder or a cone mesh.
  30112. * Please consider using the same method from the MeshBuilder class instead.
  30113. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30114. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30115. * 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.
  30116. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30117. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30119. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30120. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30121. */
  30122. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30123. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30124. if (scene !== undefined) {
  30125. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30126. updatable = scene;
  30127. }
  30128. scene = subdivisions;
  30129. subdivisions = 1;
  30130. }
  30131. var options = {
  30132. height: height,
  30133. diameterTop: diameterTop,
  30134. diameterBottom: diameterBottom,
  30135. tessellation: tessellation,
  30136. subdivisions: subdivisions,
  30137. sideOrientation: sideOrientation,
  30138. updatable: updatable
  30139. };
  30140. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30141. };
  30142. // Torus (Code from SharpDX.org)
  30143. /**
  30144. * Creates a torus mesh.
  30145. * Please consider using the same method from the MeshBuilder class instead.
  30146. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30147. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30148. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30149. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30150. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30152. */
  30153. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30154. var options = {
  30155. diameter: diameter,
  30156. thickness: thickness,
  30157. tessellation: tessellation,
  30158. sideOrientation: sideOrientation,
  30159. updatable: updatable
  30160. };
  30161. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30162. };
  30163. /**
  30164. * Creates a torus knot mesh.
  30165. * Please consider using the same method from the MeshBuilder class instead.
  30166. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30167. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30168. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30169. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30173. */
  30174. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30175. var options = {
  30176. radius: radius,
  30177. tube: tube,
  30178. radialSegments: radialSegments,
  30179. tubularSegments: tubularSegments,
  30180. p: p,
  30181. q: q,
  30182. sideOrientation: sideOrientation,
  30183. updatable: updatable
  30184. };
  30185. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30186. };
  30187. /**
  30188. * Creates a line mesh.
  30189. * Please consider using the same method from the MeshBuilder class instead.
  30190. * 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.
  30191. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30192. * The parameter `points` is an array successive Vector3.
  30193. * 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
  30194. * When updating an instance, remember that only point positions can change, not the number of points.
  30195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30196. */
  30197. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30198. if (scene === void 0) { scene = null; }
  30199. if (updatable === void 0) { updatable = false; }
  30200. if (instance === void 0) { instance = null; }
  30201. var options = {
  30202. points: points,
  30203. updatable: updatable,
  30204. instance: instance
  30205. };
  30206. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30207. };
  30208. /**
  30209. * Creates a dashed line mesh.
  30210. * Please consider using the same method from the MeshBuilder class instead.
  30211. * 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.
  30212. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30213. * The parameter `points` is an array successive Vector3.
  30214. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30215. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30216. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30217. * 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
  30218. * When updating an instance, remember that only point positions can change, not the number of points.
  30219. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30220. */
  30221. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30222. if (scene === void 0) { scene = null; }
  30223. var options = {
  30224. points: points,
  30225. dashSize: dashSize,
  30226. gapSize: gapSize,
  30227. dashNb: dashNb,
  30228. updatable: updatable,
  30229. instance: instance
  30230. };
  30231. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30232. };
  30233. /**
  30234. * Creates a polygon mesh.
  30235. * Please consider using the same method from the MeshBuilder class instead.
  30236. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30237. * 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.
  30238. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30240. * Remember you can only change the shape positions, not their number when updating a polygon.
  30241. */
  30242. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30243. var options = {
  30244. shape: shape,
  30245. holes: holes,
  30246. updatable: updatable,
  30247. sideOrientation: sideOrientation
  30248. };
  30249. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30250. };
  30251. /**
  30252. * Creates an extruded polygon mesh, with depth in the Y direction.
  30253. * Please consider using the same method from the MeshBuilder class instead.
  30254. */
  30255. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30256. var options = {
  30257. shape: shape,
  30258. holes: holes,
  30259. depth: depth,
  30260. updatable: updatable,
  30261. sideOrientation: sideOrientation
  30262. };
  30263. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30264. };
  30265. /**
  30266. * Creates an extruded shape mesh.
  30267. * 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.
  30268. * Please consider using the same method from the MeshBuilder class instead.
  30269. *
  30270. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30271. * 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
  30272. * extruded along the Z axis.
  30273. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30274. * 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.
  30275. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30276. * 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
  30277. * 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
  30278. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30279. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30280. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30281. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30282. */
  30283. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30284. if (scene === void 0) { scene = null; }
  30285. var options = {
  30286. shape: shape,
  30287. path: path,
  30288. scale: scale,
  30289. rotation: rotation,
  30290. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30291. sideOrientation: sideOrientation,
  30292. instance: instance,
  30293. updatable: updatable
  30294. };
  30295. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30296. };
  30297. /**
  30298. * Creates an custom extruded shape mesh.
  30299. * 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.
  30300. * Please consider using the same method from the MeshBuilder class instead.
  30301. *
  30302. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30303. * 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
  30304. * extruded along the Z axis.
  30305. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30306. * 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
  30307. * and the distance of this point from the begining of the path :
  30308. * ```javascript
  30309. * var rotationFunction = function(i, distance) {
  30310. * // do things
  30311. * return rotationValue; }
  30312. * ```
  30313. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30314. * 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
  30315. * and the distance of this point from the begining of the path :
  30316. * ```javascript
  30317. * var scaleFunction = function(i, distance) {
  30318. * // do things
  30319. * return scaleValue;}
  30320. * ```
  30321. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30322. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30323. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30324. * 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
  30325. * 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
  30326. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30327. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30328. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30330. */
  30331. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30332. var options = {
  30333. shape: shape,
  30334. path: path,
  30335. scaleFunction: scaleFunction,
  30336. rotationFunction: rotationFunction,
  30337. ribbonCloseArray: ribbonCloseArray,
  30338. ribbonClosePath: ribbonClosePath,
  30339. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30340. sideOrientation: sideOrientation,
  30341. instance: instance,
  30342. updatable: updatable
  30343. };
  30344. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30345. };
  30346. /**
  30347. * Creates lathe mesh.
  30348. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30349. * Please consider using the same method from the MeshBuilder class instead.
  30350. * 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
  30351. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30352. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30353. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30354. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30355. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30357. */
  30358. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30359. var options = {
  30360. shape: shape,
  30361. radius: radius,
  30362. tessellation: tessellation,
  30363. sideOrientation: sideOrientation,
  30364. updatable: updatable
  30365. };
  30366. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30367. };
  30368. /**
  30369. * Creates a plane mesh.
  30370. * Please consider using the same method from the MeshBuilder class instead.
  30371. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30372. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30373. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30375. */
  30376. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30377. var options = {
  30378. size: size,
  30379. width: size,
  30380. height: size,
  30381. sideOrientation: sideOrientation,
  30382. updatable: updatable
  30383. };
  30384. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30385. };
  30386. /**
  30387. * Creates a ground mesh.
  30388. * Please consider using the same method from the MeshBuilder class instead.
  30389. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30390. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30392. */
  30393. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30394. var options = {
  30395. width: width,
  30396. height: height,
  30397. subdivisions: subdivisions,
  30398. updatable: updatable
  30399. };
  30400. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30401. };
  30402. /**
  30403. * Creates a tiled ground mesh.
  30404. * Please consider using the same method from the MeshBuilder class instead.
  30405. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30406. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30407. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30408. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30409. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30410. * numbers of subdivisions on the ground width and height of each tile.
  30411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30412. */
  30413. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30414. var options = {
  30415. xmin: xmin,
  30416. zmin: zmin,
  30417. xmax: xmax,
  30418. zmax: zmax,
  30419. subdivisions: subdivisions,
  30420. precision: precision,
  30421. updatable: updatable
  30422. };
  30423. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30424. };
  30425. /**
  30426. * Creates a ground mesh from a height map.
  30427. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30428. * Please consider using the same method from the MeshBuilder class instead.
  30429. * The parameter `url` sets the URL of the height map image resource.
  30430. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30431. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30432. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30433. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30434. * 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).
  30435. * This function is passed the newly built mesh :
  30436. * ```javascript
  30437. * function(mesh) { // do things
  30438. * return; }
  30439. * ```
  30440. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30441. */
  30442. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30443. var options = {
  30444. width: width,
  30445. height: height,
  30446. subdivisions: subdivisions,
  30447. minHeight: minHeight,
  30448. maxHeight: maxHeight,
  30449. updatable: updatable,
  30450. onReady: onReady
  30451. };
  30452. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30453. };
  30454. /**
  30455. * Creates a tube mesh.
  30456. * 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.
  30457. * Please consider using the same method from the MeshBuilder class instead.
  30458. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30459. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30460. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30461. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30462. * 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.
  30463. * It must return a radius value (positive float) :
  30464. * ```javascript
  30465. * var radiusFunction = function(i, distance) {
  30466. * // do things
  30467. * return radius; }
  30468. * ```
  30469. * 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
  30470. * 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
  30471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30474. */
  30475. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30476. var options = {
  30477. path: path,
  30478. radius: radius,
  30479. tessellation: tessellation,
  30480. radiusFunction: radiusFunction,
  30481. arc: 1,
  30482. cap: cap,
  30483. updatable: updatable,
  30484. sideOrientation: sideOrientation,
  30485. instance: instance
  30486. };
  30487. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30488. };
  30489. /**
  30490. * Creates a polyhedron mesh.
  30491. * Please consider using the same method from the MeshBuilder class instead.
  30492. * 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
  30493. * to choose the wanted type.
  30494. * The parameter `size` (positive float, default 1) sets the polygon size.
  30495. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30496. * 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`.
  30497. * 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
  30498. * 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)`).
  30499. * 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
  30500. * 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.
  30501. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30502. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30503. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30504. */
  30505. Mesh.CreatePolyhedron = function (name, options, scene) {
  30506. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30507. };
  30508. /**
  30509. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30510. * Please consider using the same method from the MeshBuilder class instead.
  30511. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30512. * 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`).
  30513. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30514. * 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.
  30515. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30516. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30518. */
  30519. Mesh.CreateIcoSphere = function (name, options, scene) {
  30520. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30521. };
  30522. /**
  30523. * Creates a decal mesh.
  30524. * Please consider using the same method from the MeshBuilder class instead.
  30525. * 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.
  30526. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30527. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30528. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30529. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30530. */
  30531. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30532. var options = {
  30533. position: position,
  30534. normal: normal,
  30535. size: size,
  30536. angle: angle
  30537. };
  30538. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30539. };
  30540. // Skeletons
  30541. /**
  30542. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30543. */
  30544. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30545. if (!this._sourcePositions) {
  30546. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30547. if (!source) {
  30548. return this._sourcePositions;
  30549. }
  30550. this._sourcePositions = new Float32Array(source);
  30551. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30552. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30553. }
  30554. }
  30555. return this._sourcePositions;
  30556. };
  30557. /**
  30558. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30559. */
  30560. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30561. if (!this._sourceNormals) {
  30562. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30563. if (!source) {
  30564. return this._sourceNormals;
  30565. }
  30566. this._sourceNormals = new Float32Array(source);
  30567. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30568. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30569. }
  30570. }
  30571. return this._sourceNormals;
  30572. };
  30573. /**
  30574. * Updates the vertex buffer by applying transformation from the bones.
  30575. * Returns the Mesh.
  30576. *
  30577. * @param {skeleton} skeleton to apply
  30578. */
  30579. Mesh.prototype.applySkeleton = function (skeleton) {
  30580. if (!this.geometry) {
  30581. return this;
  30582. }
  30583. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30584. return this;
  30585. }
  30586. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30587. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30588. return this;
  30589. }
  30590. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30591. return this;
  30592. }
  30593. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30594. return this;
  30595. }
  30596. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30597. return this;
  30598. }
  30599. if (!this._sourcePositions) {
  30600. var submeshes = this.subMeshes.slice();
  30601. this.setPositionsForCPUSkinning();
  30602. this.subMeshes = submeshes;
  30603. }
  30604. if (!this._sourceNormals) {
  30605. this.setNormalsForCPUSkinning();
  30606. }
  30607. // positionsData checks for not being Float32Array will only pass at most once
  30608. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30609. if (!positionsData) {
  30610. return this;
  30611. }
  30612. if (!(positionsData instanceof Float32Array)) {
  30613. positionsData = new Float32Array(positionsData);
  30614. }
  30615. // normalsData checks for not being Float32Array will only pass at most once
  30616. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30617. if (!normalsData) {
  30618. return this;
  30619. }
  30620. if (!(normalsData instanceof Float32Array)) {
  30621. normalsData = new Float32Array(normalsData);
  30622. }
  30623. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30624. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30625. if (!matricesWeightsData || !matricesIndicesData) {
  30626. return this;
  30627. }
  30628. var needExtras = this.numBoneInfluencers > 4;
  30629. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30630. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30631. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30632. var tempVector3 = BABYLON.Vector3.Zero();
  30633. var finalMatrix = new BABYLON.Matrix();
  30634. var tempMatrix = new BABYLON.Matrix();
  30635. var matWeightIdx = 0;
  30636. var inf;
  30637. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30638. var weight;
  30639. for (inf = 0; inf < 4; inf++) {
  30640. weight = matricesWeightsData[matWeightIdx + inf];
  30641. if (weight > 0) {
  30642. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30643. finalMatrix.addToSelf(tempMatrix);
  30644. }
  30645. else
  30646. break;
  30647. }
  30648. if (needExtras) {
  30649. for (inf = 0; inf < 4; inf++) {
  30650. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30651. if (weight > 0) {
  30652. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30653. finalMatrix.addToSelf(tempMatrix);
  30654. }
  30655. else
  30656. break;
  30657. }
  30658. }
  30659. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30660. tempVector3.toArray(positionsData, index);
  30661. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30662. tempVector3.toArray(normalsData, index);
  30663. finalMatrix.reset();
  30664. }
  30665. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30666. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30667. return this;
  30668. };
  30669. // Tools
  30670. /**
  30671. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30672. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30673. */
  30674. Mesh.MinMax = function (meshes) {
  30675. var minVector = null;
  30676. var maxVector = null;
  30677. meshes.forEach(function (mesh, index, array) {
  30678. var boundingInfo = mesh.getBoundingInfo();
  30679. var boundingBox = boundingInfo.boundingBox;
  30680. if (!minVector || !maxVector) {
  30681. minVector = boundingBox.minimumWorld;
  30682. maxVector = boundingBox.maximumWorld;
  30683. }
  30684. else {
  30685. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30686. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30687. }
  30688. });
  30689. if (!minVector || !maxVector) {
  30690. return {
  30691. min: BABYLON.Vector3.Zero(),
  30692. max: BABYLON.Vector3.Zero()
  30693. };
  30694. }
  30695. return {
  30696. min: minVector,
  30697. max: maxVector
  30698. };
  30699. };
  30700. /**
  30701. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30702. */
  30703. Mesh.Center = function (meshesOrMinMaxVector) {
  30704. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30705. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30706. };
  30707. /**
  30708. * Merge the array of meshes into a single mesh for performance reasons.
  30709. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30710. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30711. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30712. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30713. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30714. */
  30715. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30716. if (disposeSource === void 0) { disposeSource = true; }
  30717. var index;
  30718. if (!allow32BitsIndices) {
  30719. var totalVertices = 0;
  30720. // Counting vertices
  30721. for (index = 0; index < meshes.length; index++) {
  30722. if (meshes[index]) {
  30723. totalVertices += meshes[index].getTotalVertices();
  30724. if (totalVertices > 65536) {
  30725. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30726. return null;
  30727. }
  30728. }
  30729. }
  30730. }
  30731. // Merge
  30732. var vertexData = null;
  30733. var otherVertexData;
  30734. var indiceArray = new Array();
  30735. var source = null;
  30736. for (index = 0; index < meshes.length; index++) {
  30737. if (meshes[index]) {
  30738. meshes[index].computeWorldMatrix(true);
  30739. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30740. otherVertexData.transform(meshes[index].getWorldMatrix());
  30741. if (vertexData) {
  30742. vertexData.merge(otherVertexData);
  30743. }
  30744. else {
  30745. vertexData = otherVertexData;
  30746. source = meshes[index];
  30747. }
  30748. if (subdivideWithSubMeshes) {
  30749. indiceArray.push(meshes[index].getTotalIndices());
  30750. }
  30751. }
  30752. }
  30753. source = source;
  30754. if (!meshSubclass) {
  30755. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30756. }
  30757. vertexData.applyToMesh(meshSubclass);
  30758. // Setting properties
  30759. meshSubclass.material = source.material;
  30760. meshSubclass.checkCollisions = source.checkCollisions;
  30761. // Cleaning
  30762. if (disposeSource) {
  30763. for (index = 0; index < meshes.length; index++) {
  30764. if (meshes[index]) {
  30765. meshes[index].dispose();
  30766. }
  30767. }
  30768. }
  30769. // Subdivide
  30770. if (subdivideWithSubMeshes) {
  30771. //-- Suppresions du submesh global
  30772. meshSubclass.releaseSubMeshes();
  30773. index = 0;
  30774. var offset = 0;
  30775. //-- aplique la subdivision en fonction du tableau d'indices
  30776. while (index < indiceArray.length) {
  30777. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30778. offset += indiceArray[index];
  30779. index++;
  30780. }
  30781. }
  30782. return meshSubclass;
  30783. };
  30784. // Consts
  30785. Mesh._FRONTSIDE = 0;
  30786. Mesh._BACKSIDE = 1;
  30787. Mesh._DOUBLESIDE = 2;
  30788. Mesh._DEFAULTSIDE = 0;
  30789. Mesh._NO_CAP = 0;
  30790. Mesh._CAP_START = 1;
  30791. Mesh._CAP_END = 2;
  30792. Mesh._CAP_ALL = 3;
  30793. return Mesh;
  30794. }(BABYLON.AbstractMesh));
  30795. BABYLON.Mesh = Mesh;
  30796. })(BABYLON || (BABYLON = {}));
  30797. //# sourceMappingURL=babylon.mesh.js.map
  30798. "use strict";
  30799. var BABYLON;
  30800. (function (BABYLON) {
  30801. var BaseSubMesh = /** @class */ (function () {
  30802. function BaseSubMesh() {
  30803. }
  30804. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30805. get: function () {
  30806. return this._materialEffect;
  30807. },
  30808. enumerable: true,
  30809. configurable: true
  30810. });
  30811. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30812. if (defines === void 0) { defines = null; }
  30813. if (this._materialEffect === effect) {
  30814. if (!effect) {
  30815. this._materialDefines = null;
  30816. }
  30817. return;
  30818. }
  30819. this._materialDefines = defines;
  30820. this._materialEffect = effect;
  30821. };
  30822. return BaseSubMesh;
  30823. }());
  30824. BABYLON.BaseSubMesh = BaseSubMesh;
  30825. var SubMesh = /** @class */ (function (_super) {
  30826. __extends(SubMesh, _super);
  30827. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30828. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30829. var _this = _super.call(this) || this;
  30830. _this.materialIndex = materialIndex;
  30831. _this.verticesStart = verticesStart;
  30832. _this.verticesCount = verticesCount;
  30833. _this.indexStart = indexStart;
  30834. _this.indexCount = indexCount;
  30835. _this._renderId = 0;
  30836. _this._mesh = mesh;
  30837. _this._renderingMesh = renderingMesh || mesh;
  30838. mesh.subMeshes.push(_this);
  30839. _this._trianglePlanes = [];
  30840. _this._id = mesh.subMeshes.length - 1;
  30841. if (createBoundingBox) {
  30842. _this.refreshBoundingInfo();
  30843. mesh.computeWorldMatrix(true);
  30844. }
  30845. return _this;
  30846. }
  30847. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30848. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30849. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30850. };
  30851. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30852. get: function () {
  30853. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30854. },
  30855. enumerable: true,
  30856. configurable: true
  30857. });
  30858. /**
  30859. * Returns the submesh BoudingInfo object.
  30860. */
  30861. SubMesh.prototype.getBoundingInfo = function () {
  30862. if (this.IsGlobal) {
  30863. return this._mesh.getBoundingInfo();
  30864. }
  30865. return this._boundingInfo;
  30866. };
  30867. /**
  30868. * Sets the submesh BoundingInfo.
  30869. * Return the SubMesh.
  30870. */
  30871. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30872. this._boundingInfo = boundingInfo;
  30873. return this;
  30874. };
  30875. /**
  30876. * Returns the mesh of the current submesh.
  30877. */
  30878. SubMesh.prototype.getMesh = function () {
  30879. return this._mesh;
  30880. };
  30881. /**
  30882. * Returns the rendering mesh of the submesh.
  30883. */
  30884. SubMesh.prototype.getRenderingMesh = function () {
  30885. return this._renderingMesh;
  30886. };
  30887. /**
  30888. * Returns the submesh material.
  30889. */
  30890. SubMesh.prototype.getMaterial = function () {
  30891. var rootMaterial = this._renderingMesh.material;
  30892. if (rootMaterial === null || rootMaterial === undefined) {
  30893. return this._mesh.getScene().defaultMaterial;
  30894. }
  30895. else if (rootMaterial.getSubMaterial) {
  30896. var multiMaterial = rootMaterial;
  30897. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30898. if (this._currentMaterial !== effectiveMaterial) {
  30899. this._currentMaterial = effectiveMaterial;
  30900. this._materialDefines = null;
  30901. }
  30902. return effectiveMaterial;
  30903. }
  30904. return rootMaterial;
  30905. };
  30906. // Methods
  30907. /**
  30908. * Sets a new updated BoundingInfo object to the submesh.
  30909. * Returns the SubMesh.
  30910. */
  30911. SubMesh.prototype.refreshBoundingInfo = function () {
  30912. this._lastColliderWorldVertices = null;
  30913. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30914. return this;
  30915. }
  30916. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30917. if (!data) {
  30918. this._boundingInfo = this._mesh.getBoundingInfo();
  30919. return this;
  30920. }
  30921. var indices = this._renderingMesh.getIndices();
  30922. var extend;
  30923. //is this the only submesh?
  30924. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30925. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30926. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30927. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30928. }
  30929. else {
  30930. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30931. }
  30932. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30933. return this;
  30934. };
  30935. SubMesh.prototype._checkCollision = function (collider) {
  30936. var boundingInfo = this.getBoundingInfo();
  30937. return boundingInfo._checkCollision(collider);
  30938. };
  30939. /**
  30940. * Updates the submesh BoundingInfo.
  30941. * Returns the Submesh.
  30942. */
  30943. SubMesh.prototype.updateBoundingInfo = function (world) {
  30944. var boundingInfo = this.getBoundingInfo();
  30945. if (!boundingInfo) {
  30946. this.refreshBoundingInfo();
  30947. boundingInfo = this.getBoundingInfo();
  30948. }
  30949. boundingInfo.update(world);
  30950. return this;
  30951. };
  30952. /**
  30953. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30954. * Boolean returned.
  30955. */
  30956. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30957. var boundingInfo = this.getBoundingInfo();
  30958. if (!boundingInfo) {
  30959. return false;
  30960. }
  30961. return boundingInfo.isInFrustum(frustumPlanes);
  30962. };
  30963. /**
  30964. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30965. * Boolean returned.
  30966. */
  30967. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30968. var boundingInfo = this.getBoundingInfo();
  30969. if (!boundingInfo) {
  30970. return false;
  30971. }
  30972. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30973. };
  30974. /**
  30975. * Renders the submesh.
  30976. * Returns it.
  30977. */
  30978. SubMesh.prototype.render = function (enableAlphaMode) {
  30979. this._renderingMesh.render(this, enableAlphaMode);
  30980. return this;
  30981. };
  30982. /**
  30983. * Returns a new Index Buffer.
  30984. * Type returned : WebGLBuffer.
  30985. */
  30986. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30987. if (!this._linesIndexBuffer) {
  30988. var linesIndices = [];
  30989. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30990. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30991. }
  30992. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30993. this.linesIndexCount = linesIndices.length;
  30994. }
  30995. return this._linesIndexBuffer;
  30996. };
  30997. /**
  30998. * True is the passed Ray intersects the submesh bounding box.
  30999. * Boolean returned.
  31000. */
  31001. SubMesh.prototype.canIntersects = function (ray) {
  31002. var boundingInfo = this.getBoundingInfo();
  31003. if (!boundingInfo) {
  31004. return false;
  31005. }
  31006. return ray.intersectsBox(boundingInfo.boundingBox);
  31007. };
  31008. /**
  31009. * Returns an object IntersectionInfo.
  31010. */
  31011. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31012. var intersectInfo = null;
  31013. var material = this.getMaterial();
  31014. if (!material) {
  31015. return null;
  31016. }
  31017. switch (material.fillMode) {
  31018. case BABYLON.Material.PointListDrawMode:
  31019. case BABYLON.Material.LineListDrawMode:
  31020. case BABYLON.Material.LineLoopDrawMode:
  31021. case BABYLON.Material.LineStripDrawMode:
  31022. case BABYLON.Material.TriangleFanDrawMode:
  31023. case BABYLON.Material.TriangleStripDrawMode:
  31024. return null;
  31025. }
  31026. // LineMesh first as it's also a Mesh...
  31027. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31028. var lineMesh = this._mesh;
  31029. // Line test
  31030. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31031. var p0 = positions[indices[index]];
  31032. var p1 = positions[indices[index + 1]];
  31033. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31034. if (length < 0) {
  31035. continue;
  31036. }
  31037. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31038. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31039. if (fastCheck) {
  31040. break;
  31041. }
  31042. }
  31043. }
  31044. }
  31045. else {
  31046. // Triangles test
  31047. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31048. var p0 = positions[indices[index]];
  31049. var p1 = positions[indices[index + 1]];
  31050. var p2 = positions[indices[index + 2]];
  31051. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31052. if (currentIntersectInfo) {
  31053. if (currentIntersectInfo.distance < 0) {
  31054. continue;
  31055. }
  31056. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31057. intersectInfo = currentIntersectInfo;
  31058. intersectInfo.faceId = index / 3;
  31059. if (fastCheck) {
  31060. break;
  31061. }
  31062. }
  31063. }
  31064. }
  31065. }
  31066. return intersectInfo;
  31067. };
  31068. SubMesh.prototype._rebuild = function () {
  31069. if (this._linesIndexBuffer) {
  31070. this._linesIndexBuffer = null;
  31071. }
  31072. };
  31073. // Clone
  31074. /**
  31075. * Creates a new Submesh from the passed Mesh.
  31076. */
  31077. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31078. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31079. if (!this.IsGlobal) {
  31080. var boundingInfo = this.getBoundingInfo();
  31081. if (!boundingInfo) {
  31082. return result;
  31083. }
  31084. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31085. }
  31086. return result;
  31087. };
  31088. // Dispose
  31089. /**
  31090. * Disposes the Submesh.
  31091. * Returns nothing.
  31092. */
  31093. SubMesh.prototype.dispose = function () {
  31094. if (this._linesIndexBuffer) {
  31095. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31096. this._linesIndexBuffer = null;
  31097. }
  31098. // Remove from mesh
  31099. var index = this._mesh.subMeshes.indexOf(this);
  31100. this._mesh.subMeshes.splice(index, 1);
  31101. };
  31102. // Statics
  31103. /**
  31104. * Creates a new Submesh from the passed parameters :
  31105. * - materialIndex (integer) : the index of the main mesh material.
  31106. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31107. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31108. * - mesh (Mesh) : the main mesh to create the submesh from.
  31109. * - renderingMesh (optional Mesh) : rendering mesh.
  31110. */
  31111. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31112. var minVertexIndex = Number.MAX_VALUE;
  31113. var maxVertexIndex = -Number.MAX_VALUE;
  31114. renderingMesh = (renderingMesh || mesh);
  31115. var indices = renderingMesh.getIndices();
  31116. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31117. var vertexIndex = indices[index];
  31118. if (vertexIndex < minVertexIndex)
  31119. minVertexIndex = vertexIndex;
  31120. if (vertexIndex > maxVertexIndex)
  31121. maxVertexIndex = vertexIndex;
  31122. }
  31123. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31124. };
  31125. return SubMesh;
  31126. }(BaseSubMesh));
  31127. BABYLON.SubMesh = SubMesh;
  31128. })(BABYLON || (BABYLON = {}));
  31129. //# sourceMappingURL=babylon.subMesh.js.map
  31130. "use strict";
  31131. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31132. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31133. s = arguments[i];
  31134. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31135. t[p] = s[p];
  31136. }
  31137. return t;
  31138. };
  31139. var BABYLON;
  31140. (function (BABYLON) {
  31141. /**
  31142. * Manages the defines for the Material.
  31143. */
  31144. var MaterialDefines = /** @class */ (function () {
  31145. function MaterialDefines() {
  31146. this._isDirty = true;
  31147. this._areLightsDirty = true;
  31148. this._areAttributesDirty = true;
  31149. this._areTexturesDirty = true;
  31150. this._areFresnelDirty = true;
  31151. this._areMiscDirty = true;
  31152. this._areImageProcessingDirty = true;
  31153. this._normals = false;
  31154. this._uvs = false;
  31155. this._needNormals = false;
  31156. this._needUVs = false;
  31157. }
  31158. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31159. /**
  31160. * Specifies if the material needs to be re-calculated.
  31161. */
  31162. get: function () {
  31163. return this._isDirty;
  31164. },
  31165. enumerable: true,
  31166. configurable: true
  31167. });
  31168. /**
  31169. * Marks the material to indicate that it has been re-calculated.
  31170. */
  31171. MaterialDefines.prototype.markAsProcessed = function () {
  31172. this._isDirty = false;
  31173. this._areAttributesDirty = false;
  31174. this._areTexturesDirty = false;
  31175. this._areFresnelDirty = false;
  31176. this._areLightsDirty = false;
  31177. this._areMiscDirty = false;
  31178. this._areImageProcessingDirty = false;
  31179. };
  31180. /**
  31181. * Marks the material to indicate that it needs to be re-calculated.
  31182. */
  31183. MaterialDefines.prototype.markAsUnprocessed = function () {
  31184. this._isDirty = true;
  31185. };
  31186. /**
  31187. * Marks the material to indicate all of its defines need to be re-calculated.
  31188. */
  31189. MaterialDefines.prototype.markAllAsDirty = function () {
  31190. this._areTexturesDirty = true;
  31191. this._areAttributesDirty = true;
  31192. this._areLightsDirty = true;
  31193. this._areFresnelDirty = true;
  31194. this._areMiscDirty = true;
  31195. this._areImageProcessingDirty = true;
  31196. this._isDirty = true;
  31197. };
  31198. /**
  31199. * Marks the material to indicate that image processing needs to be re-calculated.
  31200. */
  31201. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31202. this._areImageProcessingDirty = true;
  31203. this._isDirty = true;
  31204. };
  31205. /**
  31206. * Marks the material to indicate the lights need to be re-calculated.
  31207. */
  31208. MaterialDefines.prototype.markAsLightDirty = function () {
  31209. this._areLightsDirty = true;
  31210. this._isDirty = true;
  31211. };
  31212. /**
  31213. * Marks the attribute state as changed.
  31214. */
  31215. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31216. this._areAttributesDirty = true;
  31217. this._isDirty = true;
  31218. };
  31219. /**
  31220. * Marks the texture state as changed.
  31221. */
  31222. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31223. this._areTexturesDirty = true;
  31224. this._isDirty = true;
  31225. };
  31226. /**
  31227. * Marks the fresnel state as changed.
  31228. */
  31229. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31230. this._areFresnelDirty = true;
  31231. this._isDirty = true;
  31232. };
  31233. /**
  31234. * Marks the misc state as changed.
  31235. */
  31236. MaterialDefines.prototype.markAsMiscDirty = function () {
  31237. this._areMiscDirty = true;
  31238. this._isDirty = true;
  31239. };
  31240. /**
  31241. * Rebuilds the material defines.
  31242. */
  31243. MaterialDefines.prototype.rebuild = function () {
  31244. if (this._keys) {
  31245. delete this._keys;
  31246. }
  31247. this._keys = [];
  31248. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31249. var key = _a[_i];
  31250. if (key[0] === "_") {
  31251. continue;
  31252. }
  31253. this._keys.push(key);
  31254. }
  31255. };
  31256. /**
  31257. * Specifies if two material defines are equal.
  31258. * @param other - A material define instance to compare to.
  31259. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31260. */
  31261. MaterialDefines.prototype.isEqual = function (other) {
  31262. if (this._keys.length !== other._keys.length) {
  31263. return false;
  31264. }
  31265. for (var index = 0; index < this._keys.length; index++) {
  31266. var prop = this._keys[index];
  31267. if (this[prop] !== other[prop]) {
  31268. return false;
  31269. }
  31270. }
  31271. return true;
  31272. };
  31273. /**
  31274. * Clones this instance's defines to another instance.
  31275. * @param other - material defines to clone values to.
  31276. */
  31277. MaterialDefines.prototype.cloneTo = function (other) {
  31278. if (this._keys.length !== other._keys.length) {
  31279. other._keys = this._keys.slice(0);
  31280. }
  31281. for (var index = 0; index < this._keys.length; index++) {
  31282. var prop = this._keys[index];
  31283. other[prop] = this[prop];
  31284. }
  31285. };
  31286. /**
  31287. * Resets the material define values.
  31288. */
  31289. MaterialDefines.prototype.reset = function () {
  31290. for (var index = 0; index < this._keys.length; index++) {
  31291. var prop = this._keys[index];
  31292. var type = typeof this[prop];
  31293. switch (type) {
  31294. case "number":
  31295. this[prop] = 0;
  31296. break;
  31297. case "string":
  31298. this[prop] = "";
  31299. break;
  31300. default:
  31301. this[prop] = false;
  31302. break;
  31303. }
  31304. }
  31305. };
  31306. /**
  31307. * Converts the material define values to a string.
  31308. * @returns - String of material define information.
  31309. */
  31310. MaterialDefines.prototype.toString = function () {
  31311. var result = "";
  31312. for (var index = 0; index < this._keys.length; index++) {
  31313. var prop = this._keys[index];
  31314. var value = this[prop];
  31315. var type = typeof value;
  31316. switch (type) {
  31317. case "number":
  31318. case "string":
  31319. result += "#define " + prop + " " + value + "\n";
  31320. break;
  31321. default:
  31322. if (value) {
  31323. result += "#define " + prop + "\n";
  31324. }
  31325. break;
  31326. }
  31327. }
  31328. return result;
  31329. };
  31330. return MaterialDefines;
  31331. }());
  31332. BABYLON.MaterialDefines = MaterialDefines;
  31333. /**
  31334. * This offers the main features of a material in BJS.
  31335. */
  31336. var Material = /** @class */ (function () {
  31337. /**
  31338. * Creates a material instance.
  31339. * @param name - The name of the material.
  31340. * @param scene - The BJS scene to reference.
  31341. * @param doNotAdd - Specifies if the material should be added to the scene.
  31342. */
  31343. function Material(name, scene, doNotAdd) {
  31344. /**
  31345. * Specifies if the ready state should be checked on each call.
  31346. */
  31347. this.checkReadyOnEveryCall = false;
  31348. /**
  31349. * Specifies if the ready state should be checked once.
  31350. */
  31351. this.checkReadyOnlyOnce = false;
  31352. /**
  31353. * The state of the material.
  31354. */
  31355. this.state = "";
  31356. /**
  31357. * The alpha value of the material.
  31358. */
  31359. this._alpha = 1.0;
  31360. /**
  31361. * Specifies if back face culling is enabled.
  31362. */
  31363. this._backFaceCulling = true;
  31364. /**
  31365. * Specifies if the material should be serialized.
  31366. */
  31367. this.doNotSerialize = false;
  31368. /**
  31369. * Specifies if the effect should be stored on sub meshes.
  31370. */
  31371. this.storeEffectOnSubMeshes = false;
  31372. /**
  31373. * An event triggered when the material is disposed.
  31374. * @type {BABYLON.Observable}
  31375. */
  31376. this.onDisposeObservable = new BABYLON.Observable();
  31377. /**
  31378. * An event triggered when the material is bound.
  31379. * @type {BABYLON.Observable}
  31380. */
  31381. this.onBindObservable = new BABYLON.Observable();
  31382. /**
  31383. * An event triggered when the material is unbound.
  31384. * @type {BABYLON.Observable}
  31385. */
  31386. this.onUnBindObservable = new BABYLON.Observable();
  31387. /**
  31388. * Stores the value of the alpha mode.
  31389. */
  31390. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31391. /**
  31392. * Stores the state of the need depth pre-pass value.
  31393. */
  31394. this._needDepthPrePass = false;
  31395. /**
  31396. * Specifies if depth writing should be disabled.
  31397. */
  31398. this.disableDepthWrite = false;
  31399. /**
  31400. * Specifies if depth writing should be forced.
  31401. */
  31402. this.forceDepthWrite = false;
  31403. /**
  31404. * Specifies if there should be a separate pass for culling.
  31405. */
  31406. this.separateCullingPass = false;
  31407. /**
  31408. * Stores the state specifing if fog should be enabled.
  31409. */
  31410. this._fogEnabled = true;
  31411. /**
  31412. * Stores the size of points.
  31413. */
  31414. this.pointSize = 1.0;
  31415. /**
  31416. * Stores the z offset value.
  31417. */
  31418. this.zOffset = 0;
  31419. /**
  31420. * Specifies if the material was previously ready.
  31421. */
  31422. this._wasPreviouslyReady = false;
  31423. /**
  31424. * Stores the fill mode state.
  31425. */
  31426. this._fillMode = Material.TriangleFillMode;
  31427. this.name = name;
  31428. this.id = name || BABYLON.Tools.RandomId();
  31429. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31430. if (this._scene.useRightHandedSystem) {
  31431. this.sideOrientation = Material.ClockWiseSideOrientation;
  31432. }
  31433. else {
  31434. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31435. }
  31436. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31437. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31438. if (!doNotAdd) {
  31439. this._scene.materials.push(this);
  31440. }
  31441. }
  31442. Object.defineProperty(Material, "TriangleFillMode", {
  31443. /**
  31444. * Returns the triangle fill mode.
  31445. */
  31446. get: function () {
  31447. return Material._TriangleFillMode;
  31448. },
  31449. enumerable: true,
  31450. configurable: true
  31451. });
  31452. Object.defineProperty(Material, "WireFrameFillMode", {
  31453. /**
  31454. * Returns the wireframe mode.
  31455. */
  31456. get: function () {
  31457. return Material._WireFrameFillMode;
  31458. },
  31459. enumerable: true,
  31460. configurable: true
  31461. });
  31462. Object.defineProperty(Material, "PointFillMode", {
  31463. /**
  31464. * Returns the point fill mode.
  31465. */
  31466. get: function () {
  31467. return Material._PointFillMode;
  31468. },
  31469. enumerable: true,
  31470. configurable: true
  31471. });
  31472. Object.defineProperty(Material, "PointListDrawMode", {
  31473. /**
  31474. * Returns the point list draw mode.
  31475. */
  31476. get: function () {
  31477. return Material._PointListDrawMode;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. Object.defineProperty(Material, "LineListDrawMode", {
  31483. /**
  31484. * Returns the line list draw mode.
  31485. */
  31486. get: function () {
  31487. return Material._LineListDrawMode;
  31488. },
  31489. enumerable: true,
  31490. configurable: true
  31491. });
  31492. Object.defineProperty(Material, "LineLoopDrawMode", {
  31493. /**
  31494. * Returns the line loop draw mode.
  31495. */
  31496. get: function () {
  31497. return Material._LineLoopDrawMode;
  31498. },
  31499. enumerable: true,
  31500. configurable: true
  31501. });
  31502. Object.defineProperty(Material, "LineStripDrawMode", {
  31503. /**
  31504. * Returns the line strip draw mode.
  31505. */
  31506. get: function () {
  31507. return Material._LineStripDrawMode;
  31508. },
  31509. enumerable: true,
  31510. configurable: true
  31511. });
  31512. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31513. /**
  31514. * Returns the triangle strip draw mode.
  31515. */
  31516. get: function () {
  31517. return Material._TriangleStripDrawMode;
  31518. },
  31519. enumerable: true,
  31520. configurable: true
  31521. });
  31522. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31523. /**
  31524. * Returns the triangle fan draw mode.
  31525. */
  31526. get: function () {
  31527. return Material._TriangleFanDrawMode;
  31528. },
  31529. enumerable: true,
  31530. configurable: true
  31531. });
  31532. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31533. /**
  31534. * Returns the clock-wise side orientation.
  31535. */
  31536. get: function () {
  31537. return Material._ClockWiseSideOrientation;
  31538. },
  31539. enumerable: true,
  31540. configurable: true
  31541. });
  31542. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31543. /**
  31544. * Returns the counter clock-wise side orientation.
  31545. */
  31546. get: function () {
  31547. return Material._CounterClockWiseSideOrientation;
  31548. },
  31549. enumerable: true,
  31550. configurable: true
  31551. });
  31552. Object.defineProperty(Material, "TextureDirtyFlag", {
  31553. /**
  31554. * Returns the dirty texture flag value.
  31555. */
  31556. get: function () {
  31557. return Material._TextureDirtyFlag;
  31558. },
  31559. enumerable: true,
  31560. configurable: true
  31561. });
  31562. Object.defineProperty(Material, "LightDirtyFlag", {
  31563. /**
  31564. * Returns the dirty light flag value.
  31565. */
  31566. get: function () {
  31567. return Material._LightDirtyFlag;
  31568. },
  31569. enumerable: true,
  31570. configurable: true
  31571. });
  31572. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31573. /**
  31574. * Returns the dirty fresnel flag value.
  31575. */
  31576. get: function () {
  31577. return Material._FresnelDirtyFlag;
  31578. },
  31579. enumerable: true,
  31580. configurable: true
  31581. });
  31582. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31583. /**
  31584. * Returns the dirty attributes flag value.
  31585. */
  31586. get: function () {
  31587. return Material._AttributesDirtyFlag;
  31588. },
  31589. enumerable: true,
  31590. configurable: true
  31591. });
  31592. Object.defineProperty(Material, "MiscDirtyFlag", {
  31593. /**
  31594. * Returns the dirty misc flag value.
  31595. */
  31596. get: function () {
  31597. return Material._MiscDirtyFlag;
  31598. },
  31599. enumerable: true,
  31600. configurable: true
  31601. });
  31602. Object.defineProperty(Material.prototype, "alpha", {
  31603. /**
  31604. * Gets the alpha value of the material.
  31605. */
  31606. get: function () {
  31607. return this._alpha;
  31608. },
  31609. /**
  31610. * Sets the alpha value of the material.
  31611. */
  31612. set: function (value) {
  31613. if (this._alpha === value) {
  31614. return;
  31615. }
  31616. this._alpha = value;
  31617. this.markAsDirty(Material.MiscDirtyFlag);
  31618. },
  31619. enumerable: true,
  31620. configurable: true
  31621. });
  31622. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31623. /**
  31624. * Gets the back-face culling state.
  31625. */
  31626. get: function () {
  31627. return this._backFaceCulling;
  31628. },
  31629. /**
  31630. * Sets the back-face culling state.
  31631. */
  31632. set: function (value) {
  31633. if (this._backFaceCulling === value) {
  31634. return;
  31635. }
  31636. this._backFaceCulling = value;
  31637. this.markAsDirty(Material.TextureDirtyFlag);
  31638. },
  31639. enumerable: true,
  31640. configurable: true
  31641. });
  31642. Object.defineProperty(Material.prototype, "onDispose", {
  31643. /**
  31644. * Called during a dispose event.
  31645. */
  31646. set: function (callback) {
  31647. if (this._onDisposeObserver) {
  31648. this.onDisposeObservable.remove(this._onDisposeObserver);
  31649. }
  31650. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31651. },
  31652. enumerable: true,
  31653. configurable: true
  31654. });
  31655. Object.defineProperty(Material.prototype, "onBind", {
  31656. /**
  31657. * Called during a bind event.
  31658. */
  31659. set: function (callback) {
  31660. if (this._onBindObserver) {
  31661. this.onBindObservable.remove(this._onBindObserver);
  31662. }
  31663. this._onBindObserver = this.onBindObservable.add(callback);
  31664. },
  31665. enumerable: true,
  31666. configurable: true
  31667. });
  31668. Object.defineProperty(Material.prototype, "alphaMode", {
  31669. /**
  31670. * Gets the value of the alpha mode.
  31671. */
  31672. get: function () {
  31673. return this._alphaMode;
  31674. },
  31675. /**
  31676. * Sets the value of the alpha mode.
  31677. *
  31678. * | Value | Type | Description |
  31679. * | --- | --- | --- |
  31680. * | 0 | ALPHA_DISABLE | |
  31681. * | 1 | ALPHA_ADD | |
  31682. * | 2 | ALPHA_COMBINE | |
  31683. * | 3 | ALPHA_SUBTRACT | |
  31684. * | 4 | ALPHA_MULTIPLY | |
  31685. * | 5 | ALPHA_MAXIMIZED | |
  31686. * | 6 | ALPHA_ONEONE | |
  31687. * | 7 | ALPHA_PREMULTIPLIED | |
  31688. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  31689. * | 9 | ALPHA_INTERPOLATE | |
  31690. * | 10 | ALPHA_SCREENMODE | |
  31691. *
  31692. */
  31693. set: function (value) {
  31694. if (this._alphaMode === value) {
  31695. return;
  31696. }
  31697. this._alphaMode = value;
  31698. this.markAsDirty(Material.TextureDirtyFlag);
  31699. },
  31700. enumerable: true,
  31701. configurable: true
  31702. });
  31703. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31704. /**
  31705. * Gets the depth pre-pass value.
  31706. */
  31707. get: function () {
  31708. return this._needDepthPrePass;
  31709. },
  31710. /**
  31711. * Sets the need depth pre-pass value.
  31712. */
  31713. set: function (value) {
  31714. if (this._needDepthPrePass === value) {
  31715. return;
  31716. }
  31717. this._needDepthPrePass = value;
  31718. if (this._needDepthPrePass) {
  31719. this.checkReadyOnEveryCall = true;
  31720. }
  31721. },
  31722. enumerable: true,
  31723. configurable: true
  31724. });
  31725. Object.defineProperty(Material.prototype, "fogEnabled", {
  31726. /**
  31727. * Gets the value of the fog enabled state.
  31728. */
  31729. get: function () {
  31730. return this._fogEnabled;
  31731. },
  31732. /**
  31733. * Sets the state for enabling fog.
  31734. */
  31735. set: function (value) {
  31736. if (this._fogEnabled === value) {
  31737. return;
  31738. }
  31739. this._fogEnabled = value;
  31740. this.markAsDirty(Material.MiscDirtyFlag);
  31741. },
  31742. enumerable: true,
  31743. configurable: true
  31744. });
  31745. Object.defineProperty(Material.prototype, "wireframe", {
  31746. /**
  31747. * Gets a value specifying if wireframe mode is enabled.
  31748. */
  31749. get: function () {
  31750. switch (this._fillMode) {
  31751. case Material.WireFrameFillMode:
  31752. case Material.LineListDrawMode:
  31753. case Material.LineLoopDrawMode:
  31754. case Material.LineStripDrawMode:
  31755. return true;
  31756. }
  31757. return this._scene.forceWireframe;
  31758. },
  31759. /**
  31760. * Sets the state of wireframe mode.
  31761. */
  31762. set: function (value) {
  31763. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31764. },
  31765. enumerable: true,
  31766. configurable: true
  31767. });
  31768. Object.defineProperty(Material.prototype, "pointsCloud", {
  31769. /**
  31770. * Gets the value specifying if point clouds are enabled.
  31771. */
  31772. get: function () {
  31773. switch (this._fillMode) {
  31774. case Material.PointFillMode:
  31775. case Material.PointListDrawMode:
  31776. return true;
  31777. }
  31778. return this._scene.forcePointsCloud;
  31779. },
  31780. /**
  31781. * Sets the state of point cloud mode.
  31782. */
  31783. set: function (value) {
  31784. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31785. },
  31786. enumerable: true,
  31787. configurable: true
  31788. });
  31789. Object.defineProperty(Material.prototype, "fillMode", {
  31790. /**
  31791. * Gets the material fill mode.
  31792. */
  31793. get: function () {
  31794. return this._fillMode;
  31795. },
  31796. /**
  31797. * Sets the material fill mode.
  31798. */
  31799. set: function (value) {
  31800. if (this._fillMode === value) {
  31801. return;
  31802. }
  31803. this._fillMode = value;
  31804. this.markAsDirty(Material.MiscDirtyFlag);
  31805. },
  31806. enumerable: true,
  31807. configurable: true
  31808. });
  31809. /**
  31810. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31811. * subclasses should override adding information pertainent to themselves.
  31812. * @returns - String with material information.
  31813. */
  31814. Material.prototype.toString = function (fullDetails) {
  31815. var ret = "Name: " + this.name;
  31816. if (fullDetails) {
  31817. }
  31818. return ret;
  31819. };
  31820. /**
  31821. * Gets the class name of the material.
  31822. * @returns - String with the class name of the material.
  31823. */
  31824. Material.prototype.getClassName = function () {
  31825. return "Material";
  31826. };
  31827. Object.defineProperty(Material.prototype, "isFrozen", {
  31828. /**
  31829. * Specifies if updates for the material been locked.
  31830. */
  31831. get: function () {
  31832. return this.checkReadyOnlyOnce;
  31833. },
  31834. enumerable: true,
  31835. configurable: true
  31836. });
  31837. /**
  31838. * Locks updates for the material.
  31839. */
  31840. Material.prototype.freeze = function () {
  31841. this.checkReadyOnlyOnce = true;
  31842. };
  31843. /**
  31844. * Unlocks updates for the material.
  31845. */
  31846. Material.prototype.unfreeze = function () {
  31847. this.checkReadyOnlyOnce = false;
  31848. };
  31849. /**
  31850. * Specifies if the material is ready to be used.
  31851. * @param mesh - BJS mesh.
  31852. * @param useInstances - Specifies if instances should be used.
  31853. * @returns - Boolean indicating if the material is ready to be used.
  31854. */
  31855. Material.prototype.isReady = function (mesh, useInstances) {
  31856. return true;
  31857. };
  31858. /**
  31859. * Specifies that the submesh is ready to be used.
  31860. * @param mesh - BJS mesh.
  31861. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31862. * @param useInstances - Specifies that instances should be used.
  31863. * @returns - boolean indicating that the submesh is ready or not.
  31864. */
  31865. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31866. return false;
  31867. };
  31868. /**
  31869. * Returns the material effect.
  31870. * @returns - Nullable material effect.
  31871. */
  31872. Material.prototype.getEffect = function () {
  31873. return this._effect;
  31874. };
  31875. /**
  31876. * Returns the BJS scene.
  31877. * @returns - BJS Scene.
  31878. */
  31879. Material.prototype.getScene = function () {
  31880. return this._scene;
  31881. };
  31882. /**
  31883. * Specifies if the material will require alpha blending
  31884. * @returns - Boolean specifying if alpha blending is needed.
  31885. */
  31886. Material.prototype.needAlphaBlending = function () {
  31887. return (this.alpha < 1.0);
  31888. };
  31889. /**
  31890. * Specifies if the mesh will require alpha blending.
  31891. * @param mesh - BJS mesh.
  31892. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31893. */
  31894. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31895. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31896. };
  31897. /**
  31898. * Specifies if this material should be rendered in alpha test mode.
  31899. * @returns - Boolean specifying if an alpha test is needed.
  31900. */
  31901. Material.prototype.needAlphaTesting = function () {
  31902. return false;
  31903. };
  31904. /**
  31905. * Gets the texture used for the alpha test.
  31906. * @returns - Nullable alpha test texture.
  31907. */
  31908. Material.prototype.getAlphaTestTexture = function () {
  31909. return null;
  31910. };
  31911. /**
  31912. * Marks the material to indicate that it needs to be re-calculated.
  31913. */
  31914. Material.prototype.markDirty = function () {
  31915. this._wasPreviouslyReady = false;
  31916. };
  31917. Material.prototype._preBind = function (effect, overrideOrientation) {
  31918. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31919. var engine = this._scene.getEngine();
  31920. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31921. var reverse = orientation === Material.ClockWiseSideOrientation;
  31922. engine.enableEffect(effect ? effect : this._effect);
  31923. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31924. return reverse;
  31925. };
  31926. /**
  31927. * Binds the material to the mesh.
  31928. * @param world - World transformation matrix.
  31929. * @param mesh - Mesh to bind the material to.
  31930. */
  31931. Material.prototype.bind = function (world, mesh) {
  31932. };
  31933. /**
  31934. * Binds the submesh to the material.
  31935. * @param world - World transformation matrix.
  31936. * @param mesh - Mesh containing the submesh.
  31937. * @param subMesh - Submesh to bind the material to.
  31938. */
  31939. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31940. };
  31941. /**
  31942. * Binds the world matrix to the material.
  31943. * @param world - World transformation matrix.
  31944. */
  31945. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31946. };
  31947. /**
  31948. * Binds the scene's uniform buffer to the effect.
  31949. * @param effect - Effect to bind to the scene uniform buffer.
  31950. * @param sceneUbo - Scene uniform buffer.
  31951. */
  31952. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31953. sceneUbo.bindToEffect(effect, "Scene");
  31954. };
  31955. /**
  31956. * Binds the view matrix to the effect.
  31957. * @param effect - Effect to bind the view matrix to.
  31958. */
  31959. Material.prototype.bindView = function (effect) {
  31960. if (!this._useUBO) {
  31961. effect.setMatrix("view", this.getScene().getViewMatrix());
  31962. }
  31963. else {
  31964. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31965. }
  31966. };
  31967. /**
  31968. * Binds the view projection matrix to the effect.
  31969. * @param effect - Effect to bind the view projection matrix to.
  31970. */
  31971. Material.prototype.bindViewProjection = function (effect) {
  31972. if (!this._useUBO) {
  31973. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31974. }
  31975. else {
  31976. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31977. }
  31978. };
  31979. /**
  31980. * Specifies if material alpha testing should be turned on for the mesh.
  31981. * @param mesh - BJS mesh.
  31982. */
  31983. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31984. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31985. };
  31986. /**
  31987. * Processes to execute after binding the material to a mesh.
  31988. * @param mesh - BJS mesh.
  31989. */
  31990. Material.prototype._afterBind = function (mesh) {
  31991. this._scene._cachedMaterial = this;
  31992. if (mesh) {
  31993. this._scene._cachedVisibility = mesh.visibility;
  31994. }
  31995. else {
  31996. this._scene._cachedVisibility = 1;
  31997. }
  31998. if (mesh) {
  31999. this.onBindObservable.notifyObservers(mesh);
  32000. }
  32001. if (this.disableDepthWrite) {
  32002. var engine = this._scene.getEngine();
  32003. this._cachedDepthWriteState = engine.getDepthWrite();
  32004. engine.setDepthWrite(false);
  32005. }
  32006. };
  32007. /**
  32008. * Unbinds the material from the mesh.
  32009. */
  32010. Material.prototype.unbind = function () {
  32011. this.onUnBindObservable.notifyObservers(this);
  32012. if (this.disableDepthWrite) {
  32013. var engine = this._scene.getEngine();
  32014. engine.setDepthWrite(this._cachedDepthWriteState);
  32015. }
  32016. };
  32017. /**
  32018. * Gets the active textures from the material.
  32019. * @returns - Array of textures.
  32020. */
  32021. Material.prototype.getActiveTextures = function () {
  32022. return [];
  32023. };
  32024. /**
  32025. * Specifies if the material uses a texture.
  32026. * @param texture - Texture to check against the material.
  32027. * @returns - Boolean specifying if the material uses the texture.
  32028. */
  32029. Material.prototype.hasTexture = function (texture) {
  32030. return false;
  32031. };
  32032. /**
  32033. * Makes a duplicate of the material, and gives it a new name.
  32034. * @param name - Name to call the duplicated material.
  32035. * @returns - Nullable cloned material
  32036. */
  32037. Material.prototype.clone = function (name) {
  32038. return null;
  32039. };
  32040. /**
  32041. * Gets the meshes bound to the material.
  32042. * @returns - Array of meshes bound to the material.
  32043. */
  32044. Material.prototype.getBindedMeshes = function () {
  32045. var result = new Array();
  32046. for (var index = 0; index < this._scene.meshes.length; index++) {
  32047. var mesh = this._scene.meshes[index];
  32048. if (mesh.material === this) {
  32049. result.push(mesh);
  32050. }
  32051. }
  32052. return result;
  32053. };
  32054. /**
  32055. * Force shader compilation
  32056. * @param mesh - BJS mesh.
  32057. * @param onCompiled - function to execute once the material is compiled.
  32058. * @param options - options to pass to this function.
  32059. */
  32060. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32061. var _this = this;
  32062. var localOptions = __assign({ clipPlane: false }, options);
  32063. var subMesh = new BABYLON.BaseSubMesh();
  32064. var scene = this.getScene();
  32065. var checkReady = function () {
  32066. if (!_this._scene || !_this._scene.getEngine()) {
  32067. return;
  32068. }
  32069. if (subMesh._materialDefines) {
  32070. subMesh._materialDefines._renderId = -1;
  32071. }
  32072. var clipPlaneState = scene.clipPlane;
  32073. if (localOptions.clipPlane) {
  32074. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32075. }
  32076. if (_this.storeEffectOnSubMeshes) {
  32077. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32078. if (onCompiled) {
  32079. onCompiled(_this);
  32080. }
  32081. }
  32082. else {
  32083. setTimeout(checkReady, 16);
  32084. }
  32085. }
  32086. else {
  32087. if (_this.isReady(mesh)) {
  32088. if (onCompiled) {
  32089. onCompiled(_this);
  32090. }
  32091. }
  32092. else {
  32093. setTimeout(checkReady, 16);
  32094. }
  32095. }
  32096. if (localOptions.clipPlane) {
  32097. scene.clipPlane = clipPlaneState;
  32098. }
  32099. };
  32100. checkReady();
  32101. };
  32102. /**
  32103. * Force shader compilation.
  32104. * @param mesh The mesh that will use this material
  32105. * @param options Additional options for compiling the shaders
  32106. * @returns A promise that resolves when the compilation completes
  32107. */
  32108. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32109. var _this = this;
  32110. return new Promise(function (resolve) {
  32111. _this.forceCompilation(mesh, function () {
  32112. resolve();
  32113. }, options);
  32114. });
  32115. };
  32116. /**
  32117. * Marks a define in the material to indicate that it needs to be re-computed.
  32118. * @param flag - Material define flag.
  32119. */
  32120. Material.prototype.markAsDirty = function (flag) {
  32121. if (flag & Material.TextureDirtyFlag) {
  32122. this._markAllSubMeshesAsTexturesDirty();
  32123. }
  32124. if (flag & Material.LightDirtyFlag) {
  32125. this._markAllSubMeshesAsLightsDirty();
  32126. }
  32127. if (flag & Material.FresnelDirtyFlag) {
  32128. this._markAllSubMeshesAsFresnelDirty();
  32129. }
  32130. if (flag & Material.AttributesDirtyFlag) {
  32131. this._markAllSubMeshesAsAttributesDirty();
  32132. }
  32133. if (flag & Material.MiscDirtyFlag) {
  32134. this._markAllSubMeshesAsMiscDirty();
  32135. }
  32136. this.getScene().resetCachedMaterial();
  32137. };
  32138. /**
  32139. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32140. * @param func - function which checks material defines against the submeshes.
  32141. */
  32142. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32143. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32144. var mesh = _a[_i];
  32145. if (!mesh.subMeshes) {
  32146. continue;
  32147. }
  32148. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32149. var subMesh = _c[_b];
  32150. if (subMesh.getMaterial() !== this) {
  32151. continue;
  32152. }
  32153. if (!subMesh._materialDefines) {
  32154. continue;
  32155. }
  32156. func(subMesh._materialDefines);
  32157. }
  32158. }
  32159. };
  32160. /**
  32161. * Indicates that image processing needs to be re-calculated for all submeshes.
  32162. */
  32163. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32164. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32165. };
  32166. /**
  32167. * Indicates that textures need to be re-calculated for all submeshes.
  32168. */
  32169. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32170. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32171. };
  32172. /**
  32173. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32174. */
  32175. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32176. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32177. };
  32178. /**
  32179. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32180. */
  32181. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32182. this._markAllSubMeshesAsDirty(function (defines) {
  32183. defines.markAsFresnelDirty();
  32184. defines.markAsMiscDirty();
  32185. });
  32186. };
  32187. /**
  32188. * Indicates that lights need to be re-calculated for all submeshes.
  32189. */
  32190. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32191. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32192. };
  32193. /**
  32194. * Indicates that attributes need to be re-calculated for all submeshes.
  32195. */
  32196. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32197. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32198. };
  32199. /**
  32200. * Indicates that misc needs to be re-calculated for all submeshes.
  32201. */
  32202. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32203. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32204. };
  32205. /**
  32206. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32207. */
  32208. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32209. this._markAllSubMeshesAsDirty(function (defines) {
  32210. defines.markAsTexturesDirty();
  32211. defines.markAsMiscDirty();
  32212. });
  32213. };
  32214. /**
  32215. * Disposes the material.
  32216. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32217. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32218. */
  32219. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32220. // Animations
  32221. this.getScene().stopAnimation(this);
  32222. this.getScene().freeProcessedMaterials();
  32223. // Remove from scene
  32224. var index = this._scene.materials.indexOf(this);
  32225. if (index >= 0) {
  32226. this._scene.materials.splice(index, 1);
  32227. }
  32228. // Remove from meshes
  32229. for (index = 0; index < this._scene.meshes.length; index++) {
  32230. var mesh = this._scene.meshes[index];
  32231. if (mesh.material === this) {
  32232. mesh.material = null;
  32233. if (mesh.geometry) {
  32234. var geometry = (mesh.geometry);
  32235. if (this.storeEffectOnSubMeshes) {
  32236. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32237. var subMesh = _a[_i];
  32238. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32239. if (forceDisposeEffect && subMesh._materialEffect) {
  32240. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32241. }
  32242. }
  32243. }
  32244. else {
  32245. geometry._releaseVertexArrayObject(this._effect);
  32246. }
  32247. }
  32248. }
  32249. }
  32250. this._uniformBuffer.dispose();
  32251. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32252. if (forceDisposeEffect && this._effect) {
  32253. if (!this.storeEffectOnSubMeshes) {
  32254. this._scene.getEngine()._releaseEffect(this._effect);
  32255. }
  32256. this._effect = null;
  32257. }
  32258. // Callback
  32259. this.onDisposeObservable.notifyObservers(this);
  32260. this.onDisposeObservable.clear();
  32261. this.onBindObservable.clear();
  32262. this.onUnBindObservable.clear();
  32263. };
  32264. /**
  32265. * Serializes this material.
  32266. * @returns - serialized material object.
  32267. */
  32268. Material.prototype.serialize = function () {
  32269. return BABYLON.SerializationHelper.Serialize(this);
  32270. };
  32271. /**
  32272. * Creates a MultiMaterial from parse MultiMaterial data.
  32273. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32274. * @param scene - BJS scene.
  32275. * @returns - MultiMaterial.
  32276. */
  32277. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32278. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32279. multiMaterial.id = parsedMultiMaterial.id;
  32280. if (BABYLON.Tags) {
  32281. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32282. }
  32283. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32284. var subMatId = parsedMultiMaterial.materials[matIndex];
  32285. if (subMatId) {
  32286. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32287. }
  32288. else {
  32289. multiMaterial.subMaterials.push(null);
  32290. }
  32291. }
  32292. return multiMaterial;
  32293. };
  32294. /**
  32295. * Creates a material from parsed material data.
  32296. * @param parsedMaterial - Parsed material data.
  32297. * @param scene - BJS scene.
  32298. * @param rootUrl - Root URL containing the material information.
  32299. * @returns - Parsed material.
  32300. */
  32301. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32302. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32303. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32304. }
  32305. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32306. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32307. if (!BABYLON.LegacyPBRMaterial) {
  32308. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32309. return;
  32310. }
  32311. }
  32312. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32313. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32314. ;
  32315. };
  32316. // Triangle views
  32317. Material._TriangleFillMode = 0;
  32318. Material._WireFrameFillMode = 1;
  32319. Material._PointFillMode = 2;
  32320. // Draw modes
  32321. Material._PointListDrawMode = 3;
  32322. Material._LineListDrawMode = 4;
  32323. Material._LineLoopDrawMode = 5;
  32324. Material._LineStripDrawMode = 6;
  32325. Material._TriangleStripDrawMode = 7;
  32326. Material._TriangleFanDrawMode = 8;
  32327. /**
  32328. * Stores the clock-wise side orientation.
  32329. */
  32330. Material._ClockWiseSideOrientation = 0;
  32331. /**
  32332. * Stores the counter clock-wise side orientation.
  32333. */
  32334. Material._CounterClockWiseSideOrientation = 1;
  32335. /**
  32336. * The dirty texture flag value.
  32337. */
  32338. Material._TextureDirtyFlag = 1;
  32339. /**
  32340. * The dirty light flag value.
  32341. */
  32342. Material._LightDirtyFlag = 2;
  32343. /**
  32344. * The dirty fresnel flag value.
  32345. */
  32346. Material._FresnelDirtyFlag = 4;
  32347. /**
  32348. * The dirty attribute flag value.
  32349. */
  32350. Material._AttributesDirtyFlag = 8;
  32351. /**
  32352. * The dirty misc flag value.
  32353. */
  32354. Material._MiscDirtyFlag = 16;
  32355. __decorate([
  32356. BABYLON.serialize()
  32357. ], Material.prototype, "id", void 0);
  32358. __decorate([
  32359. BABYLON.serialize()
  32360. ], Material.prototype, "name", void 0);
  32361. __decorate([
  32362. BABYLON.serialize()
  32363. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32364. __decorate([
  32365. BABYLON.serialize()
  32366. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32367. __decorate([
  32368. BABYLON.serialize()
  32369. ], Material.prototype, "state", void 0);
  32370. __decorate([
  32371. BABYLON.serialize("alpha")
  32372. ], Material.prototype, "_alpha", void 0);
  32373. __decorate([
  32374. BABYLON.serialize("backFaceCulling")
  32375. ], Material.prototype, "_backFaceCulling", void 0);
  32376. __decorate([
  32377. BABYLON.serialize()
  32378. ], Material.prototype, "sideOrientation", void 0);
  32379. __decorate([
  32380. BABYLON.serialize("alphaMode")
  32381. ], Material.prototype, "_alphaMode", void 0);
  32382. __decorate([
  32383. BABYLON.serialize()
  32384. ], Material.prototype, "_needDepthPrePass", void 0);
  32385. __decorate([
  32386. BABYLON.serialize()
  32387. ], Material.prototype, "disableDepthWrite", void 0);
  32388. __decorate([
  32389. BABYLON.serialize()
  32390. ], Material.prototype, "forceDepthWrite", void 0);
  32391. __decorate([
  32392. BABYLON.serialize()
  32393. ], Material.prototype, "separateCullingPass", void 0);
  32394. __decorate([
  32395. BABYLON.serialize("fogEnabled")
  32396. ], Material.prototype, "_fogEnabled", void 0);
  32397. __decorate([
  32398. BABYLON.serialize()
  32399. ], Material.prototype, "pointSize", void 0);
  32400. __decorate([
  32401. BABYLON.serialize()
  32402. ], Material.prototype, "zOffset", void 0);
  32403. __decorate([
  32404. BABYLON.serialize()
  32405. ], Material.prototype, "wireframe", null);
  32406. __decorate([
  32407. BABYLON.serialize()
  32408. ], Material.prototype, "pointsCloud", null);
  32409. __decorate([
  32410. BABYLON.serialize()
  32411. ], Material.prototype, "fillMode", null);
  32412. return Material;
  32413. }());
  32414. BABYLON.Material = Material;
  32415. })(BABYLON || (BABYLON = {}));
  32416. //# sourceMappingURL=babylon.material.js.map
  32417. "use strict";
  32418. var BABYLON;
  32419. (function (BABYLON) {
  32420. var UniformBuffer = /** @class */ (function () {
  32421. /**
  32422. * Uniform buffer objects.
  32423. *
  32424. * Handles blocks of uniform on the GPU.
  32425. *
  32426. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32427. *
  32428. * For more information, please refer to :
  32429. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32430. */
  32431. function UniformBuffer(engine, data, dynamic) {
  32432. this._engine = engine;
  32433. this._noUBO = !engine.supportsUniformBuffers;
  32434. this._dynamic = dynamic;
  32435. this._data = data || [];
  32436. this._uniformLocations = {};
  32437. this._uniformSizes = {};
  32438. this._uniformLocationPointer = 0;
  32439. this._needSync = false;
  32440. if (this._noUBO) {
  32441. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32442. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32443. this.updateFloat = this._updateFloatForEffect;
  32444. this.updateFloat2 = this._updateFloat2ForEffect;
  32445. this.updateFloat3 = this._updateFloat3ForEffect;
  32446. this.updateFloat4 = this._updateFloat4ForEffect;
  32447. this.updateMatrix = this._updateMatrixForEffect;
  32448. this.updateVector3 = this._updateVector3ForEffect;
  32449. this.updateVector4 = this._updateVector4ForEffect;
  32450. this.updateColor3 = this._updateColor3ForEffect;
  32451. this.updateColor4 = this._updateColor4ForEffect;
  32452. }
  32453. else {
  32454. this._engine._uniformBuffers.push(this);
  32455. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32456. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32457. this.updateFloat = this._updateFloatForUniform;
  32458. this.updateFloat2 = this._updateFloat2ForUniform;
  32459. this.updateFloat3 = this._updateFloat3ForUniform;
  32460. this.updateFloat4 = this._updateFloat4ForUniform;
  32461. this.updateMatrix = this._updateMatrixForUniform;
  32462. this.updateVector3 = this._updateVector3ForUniform;
  32463. this.updateVector4 = this._updateVector4ForUniform;
  32464. this.updateColor3 = this._updateColor3ForUniform;
  32465. this.updateColor4 = this._updateColor4ForUniform;
  32466. }
  32467. }
  32468. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32469. // Properties
  32470. /**
  32471. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32472. * or just falling back on setUniformXXX calls.
  32473. */
  32474. get: function () {
  32475. return !this._noUBO;
  32476. },
  32477. enumerable: true,
  32478. configurable: true
  32479. });
  32480. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32481. /**
  32482. * Indicates if the WebGL underlying uniform buffer is in sync
  32483. * with the javascript cache data.
  32484. */
  32485. get: function () {
  32486. return !this._needSync;
  32487. },
  32488. enumerable: true,
  32489. configurable: true
  32490. });
  32491. /**
  32492. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32493. * Also, a dynamic UniformBuffer will disable cache verification and always
  32494. * update the underlying WebGL uniform buffer to the GPU.
  32495. */
  32496. UniformBuffer.prototype.isDynamic = function () {
  32497. return this._dynamic !== undefined;
  32498. };
  32499. /**
  32500. * The data cache on JS side.
  32501. */
  32502. UniformBuffer.prototype.getData = function () {
  32503. return this._bufferData;
  32504. };
  32505. /**
  32506. * The underlying WebGL Uniform buffer.
  32507. */
  32508. UniformBuffer.prototype.getBuffer = function () {
  32509. return this._buffer;
  32510. };
  32511. /**
  32512. * std140 layout specifies how to align data within an UBO structure.
  32513. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32514. * for specs.
  32515. */
  32516. UniformBuffer.prototype._fillAlignment = function (size) {
  32517. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32518. // and 4x4 matrices
  32519. // TODO : change if other types are used
  32520. var alignment;
  32521. if (size <= 2) {
  32522. alignment = size;
  32523. }
  32524. else {
  32525. alignment = 4;
  32526. }
  32527. if ((this._uniformLocationPointer % alignment) !== 0) {
  32528. var oldPointer = this._uniformLocationPointer;
  32529. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32530. var diff = this._uniformLocationPointer - oldPointer;
  32531. for (var i = 0; i < diff; i++) {
  32532. this._data.push(0);
  32533. }
  32534. }
  32535. };
  32536. /**
  32537. * Adds an uniform in the buffer.
  32538. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32539. * for the layout to be correct !
  32540. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32541. * @param {number|number[]} size Data size, or data directly.
  32542. */
  32543. UniformBuffer.prototype.addUniform = function (name, size) {
  32544. if (this._noUBO) {
  32545. return;
  32546. }
  32547. if (this._uniformLocations[name] !== undefined) {
  32548. // Already existing uniform
  32549. return;
  32550. }
  32551. // This function must be called in the order of the shader layout !
  32552. // size can be the size of the uniform, or data directly
  32553. var data;
  32554. if (size instanceof Array) {
  32555. data = size;
  32556. size = data.length;
  32557. }
  32558. else {
  32559. size = size;
  32560. data = [];
  32561. // Fill with zeros
  32562. for (var i = 0; i < size; i++) {
  32563. data.push(0);
  32564. }
  32565. }
  32566. this._fillAlignment(size);
  32567. this._uniformSizes[name] = size;
  32568. this._uniformLocations[name] = this._uniformLocationPointer;
  32569. this._uniformLocationPointer += size;
  32570. for (var i = 0; i < size; i++) {
  32571. this._data.push(data[i]);
  32572. }
  32573. this._needSync = true;
  32574. };
  32575. /**
  32576. * Wrapper for addUniform.
  32577. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32578. * @param {Matrix} mat A 4x4 matrix.
  32579. */
  32580. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32581. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32582. };
  32583. /**
  32584. * Wrapper for addUniform.
  32585. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32586. * @param {number} x
  32587. * @param {number} y
  32588. */
  32589. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32590. var temp = [x, y];
  32591. this.addUniform(name, temp);
  32592. };
  32593. /**
  32594. * Wrapper for addUniform.
  32595. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32596. * @param {number} x
  32597. * @param {number} y
  32598. * @param {number} z
  32599. */
  32600. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32601. var temp = [x, y, z];
  32602. this.addUniform(name, temp);
  32603. };
  32604. /**
  32605. * Wrapper for addUniform.
  32606. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32607. * @param {Color3} color
  32608. */
  32609. UniformBuffer.prototype.addColor3 = function (name, color) {
  32610. var temp = new Array();
  32611. color.toArray(temp);
  32612. this.addUniform(name, temp);
  32613. };
  32614. /**
  32615. * Wrapper for addUniform.
  32616. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32617. * @param {Color3} color
  32618. * @param {number} alpha
  32619. */
  32620. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32621. var temp = new Array();
  32622. color.toArray(temp);
  32623. temp.push(alpha);
  32624. this.addUniform(name, temp);
  32625. };
  32626. /**
  32627. * Wrapper for addUniform.
  32628. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32629. * @param {Vector3} vector
  32630. */
  32631. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32632. var temp = new Array();
  32633. vector.toArray(temp);
  32634. this.addUniform(name, temp);
  32635. };
  32636. /**
  32637. * Wrapper for addUniform.
  32638. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32639. */
  32640. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32641. this.addUniform(name, 12);
  32642. };
  32643. /**
  32644. * Wrapper for addUniform.
  32645. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32646. */
  32647. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32648. this.addUniform(name, 8);
  32649. };
  32650. /**
  32651. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32652. */
  32653. UniformBuffer.prototype.create = function () {
  32654. if (this._noUBO) {
  32655. return;
  32656. }
  32657. if (this._buffer) {
  32658. return; // nothing to do
  32659. }
  32660. // See spec, alignment must be filled as a vec4
  32661. this._fillAlignment(4);
  32662. this._bufferData = new Float32Array(this._data);
  32663. this._rebuild();
  32664. this._needSync = true;
  32665. };
  32666. UniformBuffer.prototype._rebuild = function () {
  32667. if (this._noUBO) {
  32668. return;
  32669. }
  32670. if (this._dynamic) {
  32671. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32672. }
  32673. else {
  32674. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32675. }
  32676. };
  32677. /**
  32678. * Updates the WebGL Uniform Buffer on the GPU.
  32679. * If the `dynamic` flag is set to true, no cache comparison is done.
  32680. * Otherwise, the buffer will be updated only if the cache differs.
  32681. */
  32682. UniformBuffer.prototype.update = function () {
  32683. if (!this._buffer) {
  32684. this.create();
  32685. return;
  32686. }
  32687. if (!this._dynamic && !this._needSync) {
  32688. return;
  32689. }
  32690. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32691. this._needSync = false;
  32692. };
  32693. /**
  32694. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32695. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32696. * @param {number[]|Float32Array} data Flattened data
  32697. * @param {number} size Size of the data.
  32698. */
  32699. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32700. var location = this._uniformLocations[uniformName];
  32701. if (location === undefined) {
  32702. if (this._buffer) {
  32703. // Cannot add an uniform if the buffer is already created
  32704. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32705. return;
  32706. }
  32707. this.addUniform(uniformName, size);
  32708. location = this._uniformLocations[uniformName];
  32709. }
  32710. if (!this._buffer) {
  32711. this.create();
  32712. }
  32713. if (!this._dynamic) {
  32714. // Cache for static uniform buffers
  32715. var changed = false;
  32716. for (var i = 0; i < size; i++) {
  32717. if (this._bufferData[location + i] !== data[i]) {
  32718. changed = true;
  32719. this._bufferData[location + i] = data[i];
  32720. }
  32721. }
  32722. this._needSync = this._needSync || changed;
  32723. }
  32724. else {
  32725. // No cache for dynamic
  32726. for (var i = 0; i < size; i++) {
  32727. this._bufferData[location + i] = data[i];
  32728. }
  32729. }
  32730. };
  32731. // Update methods
  32732. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32733. // To match std140, matrix must be realigned
  32734. for (var i = 0; i < 3; i++) {
  32735. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32736. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32737. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32738. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32739. }
  32740. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32741. };
  32742. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32743. this._currentEffect.setMatrix3x3(name, matrix);
  32744. };
  32745. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32746. this._currentEffect.setMatrix2x2(name, matrix);
  32747. };
  32748. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32749. // To match std140, matrix must be realigned
  32750. for (var i = 0; i < 2; i++) {
  32751. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32752. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32753. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32754. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32755. }
  32756. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32757. };
  32758. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32759. this._currentEffect.setFloat(name, x);
  32760. };
  32761. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32762. UniformBuffer._tempBuffer[0] = x;
  32763. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32764. };
  32765. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32766. if (suffix === void 0) { suffix = ""; }
  32767. this._currentEffect.setFloat2(name + suffix, x, y);
  32768. };
  32769. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32770. if (suffix === void 0) { suffix = ""; }
  32771. UniformBuffer._tempBuffer[0] = x;
  32772. UniformBuffer._tempBuffer[1] = y;
  32773. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32774. };
  32775. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32776. if (suffix === void 0) { suffix = ""; }
  32777. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32778. };
  32779. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32780. if (suffix === void 0) { suffix = ""; }
  32781. UniformBuffer._tempBuffer[0] = x;
  32782. UniformBuffer._tempBuffer[1] = y;
  32783. UniformBuffer._tempBuffer[2] = z;
  32784. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32785. };
  32786. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32787. if (suffix === void 0) { suffix = ""; }
  32788. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32789. };
  32790. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32791. if (suffix === void 0) { suffix = ""; }
  32792. UniformBuffer._tempBuffer[0] = x;
  32793. UniformBuffer._tempBuffer[1] = y;
  32794. UniformBuffer._tempBuffer[2] = z;
  32795. UniformBuffer._tempBuffer[3] = w;
  32796. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32797. };
  32798. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32799. this._currentEffect.setMatrix(name, mat);
  32800. };
  32801. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32802. this.updateUniform(name, mat.toArray(), 16);
  32803. };
  32804. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32805. this._currentEffect.setVector3(name, vector);
  32806. };
  32807. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32808. vector.toArray(UniformBuffer._tempBuffer);
  32809. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32810. };
  32811. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32812. this._currentEffect.setVector4(name, vector);
  32813. };
  32814. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32815. vector.toArray(UniformBuffer._tempBuffer);
  32816. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32817. };
  32818. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32819. if (suffix === void 0) { suffix = ""; }
  32820. this._currentEffect.setColor3(name + suffix, color);
  32821. };
  32822. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32823. if (suffix === void 0) { suffix = ""; }
  32824. color.toArray(UniformBuffer._tempBuffer);
  32825. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32826. };
  32827. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32828. if (suffix === void 0) { suffix = ""; }
  32829. this._currentEffect.setColor4(name + suffix, color, alpha);
  32830. };
  32831. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32832. if (suffix === void 0) { suffix = ""; }
  32833. color.toArray(UniformBuffer._tempBuffer);
  32834. UniformBuffer._tempBuffer[3] = alpha;
  32835. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32836. };
  32837. /**
  32838. * Sets a sampler uniform on the effect.
  32839. * @param {string} name Name of the sampler.
  32840. * @param {Texture} texture
  32841. */
  32842. UniformBuffer.prototype.setTexture = function (name, texture) {
  32843. this._currentEffect.setTexture(name, texture);
  32844. };
  32845. /**
  32846. * Directly updates the value of the uniform in the cache AND on the GPU.
  32847. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32848. * @param {number[]|Float32Array} data Flattened data
  32849. */
  32850. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32851. this.updateUniform(uniformName, data, data.length);
  32852. this.update();
  32853. };
  32854. /**
  32855. * Binds this uniform buffer to an effect.
  32856. * @param {Effect} effect
  32857. * @param {string} name Name of the uniform block in the shader.
  32858. */
  32859. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32860. this._currentEffect = effect;
  32861. if (this._noUBO || !this._buffer) {
  32862. return;
  32863. }
  32864. effect.bindUniformBuffer(this._buffer, name);
  32865. };
  32866. /**
  32867. * Disposes the uniform buffer.
  32868. */
  32869. UniformBuffer.prototype.dispose = function () {
  32870. if (this._noUBO) {
  32871. return;
  32872. }
  32873. var index = this._engine._uniformBuffers.indexOf(this);
  32874. if (index !== -1) {
  32875. this._engine._uniformBuffers.splice(index, 1);
  32876. }
  32877. if (!this._buffer) {
  32878. return;
  32879. }
  32880. if (this._engine._releaseBuffer(this._buffer)) {
  32881. this._buffer = null;
  32882. }
  32883. };
  32884. // Pool for avoiding memory leaks
  32885. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32886. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32887. return UniformBuffer;
  32888. }());
  32889. BABYLON.UniformBuffer = UniformBuffer;
  32890. })(BABYLON || (BABYLON = {}));
  32891. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32892. "use strict";
  32893. var BABYLON;
  32894. (function (BABYLON) {
  32895. var VertexData = /** @class */ (function () {
  32896. function VertexData() {
  32897. }
  32898. VertexData.prototype.set = function (data, kind) {
  32899. switch (kind) {
  32900. case BABYLON.VertexBuffer.PositionKind:
  32901. this.positions = data;
  32902. break;
  32903. case BABYLON.VertexBuffer.NormalKind:
  32904. this.normals = data;
  32905. break;
  32906. case BABYLON.VertexBuffer.TangentKind:
  32907. this.tangents = data;
  32908. break;
  32909. case BABYLON.VertexBuffer.UVKind:
  32910. this.uvs = data;
  32911. break;
  32912. case BABYLON.VertexBuffer.UV2Kind:
  32913. this.uvs2 = data;
  32914. break;
  32915. case BABYLON.VertexBuffer.UV3Kind:
  32916. this.uvs3 = data;
  32917. break;
  32918. case BABYLON.VertexBuffer.UV4Kind:
  32919. this.uvs4 = data;
  32920. break;
  32921. case BABYLON.VertexBuffer.UV5Kind:
  32922. this.uvs5 = data;
  32923. break;
  32924. case BABYLON.VertexBuffer.UV6Kind:
  32925. this.uvs6 = data;
  32926. break;
  32927. case BABYLON.VertexBuffer.ColorKind:
  32928. this.colors = data;
  32929. break;
  32930. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32931. this.matricesIndices = data;
  32932. break;
  32933. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32934. this.matricesWeights = data;
  32935. break;
  32936. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32937. this.matricesIndicesExtra = data;
  32938. break;
  32939. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32940. this.matricesWeightsExtra = data;
  32941. break;
  32942. }
  32943. };
  32944. /**
  32945. * Associates the vertexData to the passed Mesh.
  32946. * Sets it as updatable or not (default `false`).
  32947. * Returns the VertexData.
  32948. */
  32949. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32950. this._applyTo(mesh, updatable);
  32951. return this;
  32952. };
  32953. /**
  32954. * Associates the vertexData to the passed Geometry.
  32955. * Sets it as updatable or not (default `false`).
  32956. * Returns the VertexData.
  32957. */
  32958. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32959. this._applyTo(geometry, updatable);
  32960. return this;
  32961. };
  32962. /**
  32963. * Updates the associated mesh.
  32964. * Returns the VertexData.
  32965. */
  32966. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32967. this._update(mesh);
  32968. return this;
  32969. };
  32970. /**
  32971. * Updates the associated geometry.
  32972. * Returns the VertexData.
  32973. */
  32974. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32975. this._update(geometry);
  32976. return this;
  32977. };
  32978. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32979. if (updatable === void 0) { updatable = false; }
  32980. if (this.positions) {
  32981. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32982. }
  32983. if (this.normals) {
  32984. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32985. }
  32986. if (this.tangents) {
  32987. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32988. }
  32989. if (this.uvs) {
  32990. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32991. }
  32992. if (this.uvs2) {
  32993. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32994. }
  32995. if (this.uvs3) {
  32996. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32997. }
  32998. if (this.uvs4) {
  32999. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33000. }
  33001. if (this.uvs5) {
  33002. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33003. }
  33004. if (this.uvs6) {
  33005. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33006. }
  33007. if (this.colors) {
  33008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33009. }
  33010. if (this.matricesIndices) {
  33011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33012. }
  33013. if (this.matricesWeights) {
  33014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33015. }
  33016. if (this.matricesIndicesExtra) {
  33017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33018. }
  33019. if (this.matricesWeightsExtra) {
  33020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33021. }
  33022. if (this.indices) {
  33023. meshOrGeometry.setIndices(this.indices, null, updatable);
  33024. }
  33025. return this;
  33026. };
  33027. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33028. if (this.positions) {
  33029. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33030. }
  33031. if (this.normals) {
  33032. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33033. }
  33034. if (this.tangents) {
  33035. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33036. }
  33037. if (this.uvs) {
  33038. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33039. }
  33040. if (this.uvs2) {
  33041. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33042. }
  33043. if (this.uvs3) {
  33044. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33045. }
  33046. if (this.uvs4) {
  33047. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33048. }
  33049. if (this.uvs5) {
  33050. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33051. }
  33052. if (this.uvs6) {
  33053. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33054. }
  33055. if (this.colors) {
  33056. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33057. }
  33058. if (this.matricesIndices) {
  33059. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33060. }
  33061. if (this.matricesWeights) {
  33062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33063. }
  33064. if (this.matricesIndicesExtra) {
  33065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33066. }
  33067. if (this.matricesWeightsExtra) {
  33068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33069. }
  33070. if (this.indices) {
  33071. meshOrGeometry.setIndices(this.indices, null);
  33072. }
  33073. return this;
  33074. };
  33075. /**
  33076. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33077. * Returns the VertexData.
  33078. */
  33079. VertexData.prototype.transform = function (matrix) {
  33080. var transformed = BABYLON.Vector3.Zero();
  33081. var index;
  33082. if (this.positions) {
  33083. var position = BABYLON.Vector3.Zero();
  33084. for (index = 0; index < this.positions.length; index += 3) {
  33085. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33086. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33087. this.positions[index] = transformed.x;
  33088. this.positions[index + 1] = transformed.y;
  33089. this.positions[index + 2] = transformed.z;
  33090. }
  33091. }
  33092. if (this.normals) {
  33093. var normal = BABYLON.Vector3.Zero();
  33094. for (index = 0; index < this.normals.length; index += 3) {
  33095. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33096. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33097. this.normals[index] = transformed.x;
  33098. this.normals[index + 1] = transformed.y;
  33099. this.normals[index + 2] = transformed.z;
  33100. }
  33101. }
  33102. if (this.tangents) {
  33103. var tangent = BABYLON.Vector4.Zero();
  33104. var tangentTransformed = BABYLON.Vector4.Zero();
  33105. for (index = 0; index < this.tangents.length; index += 4) {
  33106. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33107. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33108. this.tangents[index] = tangentTransformed.x;
  33109. this.tangents[index + 1] = tangentTransformed.y;
  33110. this.tangents[index + 2] = tangentTransformed.z;
  33111. this.tangents[index + 3] = tangentTransformed.w;
  33112. }
  33113. }
  33114. return this;
  33115. };
  33116. /**
  33117. * Merges the passed VertexData into the current one.
  33118. * Returns the modified VertexData.
  33119. */
  33120. VertexData.prototype.merge = function (other) {
  33121. this._validate();
  33122. other._validate();
  33123. if (!this.normals !== !other.normals ||
  33124. !this.tangents !== !other.tangents ||
  33125. !this.uvs !== !other.uvs ||
  33126. !this.uvs2 !== !other.uvs2 ||
  33127. !this.uvs3 !== !other.uvs3 ||
  33128. !this.uvs4 !== !other.uvs4 ||
  33129. !this.uvs5 !== !other.uvs5 ||
  33130. !this.uvs6 !== !other.uvs6 ||
  33131. !this.colors !== !other.colors ||
  33132. !this.matricesIndices !== !other.matricesIndices ||
  33133. !this.matricesWeights !== !other.matricesWeights ||
  33134. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33135. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33136. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33137. }
  33138. if (other.indices) {
  33139. if (!this.indices) {
  33140. this.indices = [];
  33141. }
  33142. var offset = this.positions ? this.positions.length / 3 : 0;
  33143. for (var index = 0; index < other.indices.length; index++) {
  33144. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33145. this.indices.push(other.indices[index] + offset);
  33146. }
  33147. }
  33148. this.positions = this._mergeElement(this.positions, other.positions);
  33149. this.normals = this._mergeElement(this.normals, other.normals);
  33150. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33151. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33152. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33153. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33154. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33155. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33156. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33157. this.colors = this._mergeElement(this.colors, other.colors);
  33158. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33159. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33160. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33161. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33162. return this;
  33163. };
  33164. VertexData.prototype._mergeElement = function (source, other) {
  33165. if (!source) {
  33166. return other;
  33167. }
  33168. if (!other) {
  33169. return source;
  33170. }
  33171. var len = other.length + source.length;
  33172. var isSrcTypedArray = source instanceof Float32Array;
  33173. var isOthTypedArray = other instanceof Float32Array;
  33174. // use non-loop method when the source is Float32Array
  33175. if (isSrcTypedArray) {
  33176. var ret32 = new Float32Array(len);
  33177. ret32.set(source);
  33178. ret32.set(other, source.length);
  33179. return ret32;
  33180. // source is number[], when other is also use concat
  33181. }
  33182. else if (!isOthTypedArray) {
  33183. return source.concat(other);
  33184. // source is a number[], but other is a Float32Array, loop required
  33185. }
  33186. else {
  33187. var ret = source.slice(0); // copy source to a separate array
  33188. for (var i = 0, len = other.length; i < len; i++) {
  33189. ret.push(other[i]);
  33190. }
  33191. return ret;
  33192. }
  33193. };
  33194. VertexData.prototype._validate = function () {
  33195. if (!this.positions) {
  33196. throw new Error("Positions are required");
  33197. }
  33198. var getElementCount = function (kind, values) {
  33199. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33200. if ((values.length % stride) !== 0) {
  33201. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33202. }
  33203. return values.length / stride;
  33204. };
  33205. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33206. var validateElementCount = function (kind, values) {
  33207. var elementCount = getElementCount(kind, values);
  33208. if (elementCount !== positionsElementCount) {
  33209. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33210. }
  33211. };
  33212. if (this.normals)
  33213. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33214. if (this.tangents)
  33215. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33216. if (this.uvs)
  33217. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33218. if (this.uvs2)
  33219. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33220. if (this.uvs3)
  33221. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33222. if (this.uvs4)
  33223. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33224. if (this.uvs5)
  33225. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33226. if (this.uvs6)
  33227. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33228. if (this.colors)
  33229. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33230. if (this.matricesIndices)
  33231. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33232. if (this.matricesWeights)
  33233. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33234. if (this.matricesIndicesExtra)
  33235. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33236. if (this.matricesWeightsExtra)
  33237. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33238. };
  33239. /**
  33240. * Serializes the VertexData.
  33241. * Returns a serialized object.
  33242. */
  33243. VertexData.prototype.serialize = function () {
  33244. var serializationObject = this.serialize();
  33245. if (this.positions) {
  33246. serializationObject.positions = this.positions;
  33247. }
  33248. if (this.normals) {
  33249. serializationObject.normals = this.normals;
  33250. }
  33251. if (this.tangents) {
  33252. serializationObject.tangents = this.tangents;
  33253. }
  33254. if (this.uvs) {
  33255. serializationObject.uvs = this.uvs;
  33256. }
  33257. if (this.uvs2) {
  33258. serializationObject.uvs2 = this.uvs2;
  33259. }
  33260. if (this.uvs3) {
  33261. serializationObject.uvs3 = this.uvs3;
  33262. }
  33263. if (this.uvs4) {
  33264. serializationObject.uvs4 = this.uvs4;
  33265. }
  33266. if (this.uvs5) {
  33267. serializationObject.uvs5 = this.uvs5;
  33268. }
  33269. if (this.uvs6) {
  33270. serializationObject.uvs6 = this.uvs6;
  33271. }
  33272. if (this.colors) {
  33273. serializationObject.colors = this.colors;
  33274. }
  33275. if (this.matricesIndices) {
  33276. serializationObject.matricesIndices = this.matricesIndices;
  33277. serializationObject.matricesIndices._isExpanded = true;
  33278. }
  33279. if (this.matricesWeights) {
  33280. serializationObject.matricesWeights = this.matricesWeights;
  33281. }
  33282. if (this.matricesIndicesExtra) {
  33283. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33284. serializationObject.matricesIndicesExtra._isExpanded = true;
  33285. }
  33286. if (this.matricesWeightsExtra) {
  33287. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33288. }
  33289. serializationObject.indices = this.indices;
  33290. return serializationObject;
  33291. };
  33292. // Statics
  33293. /**
  33294. * Returns the object VertexData associated to the passed mesh.
  33295. */
  33296. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33297. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33298. };
  33299. /**
  33300. * Returns the object VertexData associated to the passed geometry.
  33301. */
  33302. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33303. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33304. };
  33305. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33306. var result = new VertexData();
  33307. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33308. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33309. }
  33310. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33311. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33312. }
  33313. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33314. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33315. }
  33316. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33317. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33318. }
  33319. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33320. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33321. }
  33322. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33323. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33324. }
  33325. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33326. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33327. }
  33328. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33329. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33330. }
  33331. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33332. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33333. }
  33334. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33335. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33336. }
  33337. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33338. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33339. }
  33340. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33341. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33342. }
  33343. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33344. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33345. }
  33346. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33347. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33348. }
  33349. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33350. return result;
  33351. };
  33352. /**
  33353. * Creates the vertexData of the Ribbon.
  33354. */
  33355. VertexData.CreateRibbon = function (options) {
  33356. var pathArray = options.pathArray;
  33357. var closeArray = options.closeArray || false;
  33358. var closePath = options.closePath || false;
  33359. var invertUV = options.invertUV || false;
  33360. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33361. var offset = options.offset || defaultOffset;
  33362. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33363. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33364. var customUV = options.uvs;
  33365. var customColors = options.colors;
  33366. var positions = [];
  33367. var indices = [];
  33368. var normals = [];
  33369. var uvs = [];
  33370. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33371. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33372. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33373. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33374. var minlg; // minimal length among all paths from pathArray
  33375. var lg = []; // array of path lengths : nb of vertex per path
  33376. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33377. var p; // path iterator
  33378. var i; // point iterator
  33379. var j; // point iterator
  33380. // if single path in pathArray
  33381. if (pathArray.length < 2) {
  33382. var ar1 = [];
  33383. var ar2 = [];
  33384. for (i = 0; i < pathArray[0].length - offset; i++) {
  33385. ar1.push(pathArray[0][i]);
  33386. ar2.push(pathArray[0][i + offset]);
  33387. }
  33388. pathArray = [ar1, ar2];
  33389. }
  33390. // positions and horizontal distances (u)
  33391. var idc = 0;
  33392. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33393. var path;
  33394. var l;
  33395. minlg = pathArray[0].length;
  33396. var vectlg;
  33397. var dist;
  33398. for (p = 0; p < pathArray.length; p++) {
  33399. uTotalDistance[p] = 0;
  33400. us[p] = [0];
  33401. path = pathArray[p];
  33402. l = path.length;
  33403. minlg = (minlg < l) ? minlg : l;
  33404. j = 0;
  33405. while (j < l) {
  33406. positions.push(path[j].x, path[j].y, path[j].z);
  33407. if (j > 0) {
  33408. vectlg = path[j].subtract(path[j - 1]).length();
  33409. dist = vectlg + uTotalDistance[p];
  33410. us[p].push(dist);
  33411. uTotalDistance[p] = dist;
  33412. }
  33413. j++;
  33414. }
  33415. if (closePath) {
  33416. j--;
  33417. positions.push(path[0].x, path[0].y, path[0].z);
  33418. vectlg = path[j].subtract(path[0]).length();
  33419. dist = vectlg + uTotalDistance[p];
  33420. us[p].push(dist);
  33421. uTotalDistance[p] = dist;
  33422. }
  33423. lg[p] = l + closePathCorr;
  33424. idx[p] = idc;
  33425. idc += (l + closePathCorr);
  33426. }
  33427. // vertical distances (v)
  33428. var path1;
  33429. var path2;
  33430. var vertex1 = null;
  33431. var vertex2 = null;
  33432. for (i = 0; i < minlg + closePathCorr; i++) {
  33433. vTotalDistance[i] = 0;
  33434. vs[i] = [0];
  33435. for (p = 0; p < pathArray.length - 1; p++) {
  33436. path1 = pathArray[p];
  33437. path2 = pathArray[p + 1];
  33438. if (i === minlg) {
  33439. vertex1 = path1[0];
  33440. vertex2 = path2[0];
  33441. }
  33442. else {
  33443. vertex1 = path1[i];
  33444. vertex2 = path2[i];
  33445. }
  33446. vectlg = vertex2.subtract(vertex1).length();
  33447. dist = vectlg + vTotalDistance[i];
  33448. vs[i].push(dist);
  33449. vTotalDistance[i] = dist;
  33450. }
  33451. if (closeArray && vertex2 && vertex1) {
  33452. path1 = pathArray[p];
  33453. path2 = pathArray[0];
  33454. if (i === minlg) {
  33455. vertex2 = path2[0];
  33456. }
  33457. vectlg = vertex2.subtract(vertex1).length();
  33458. dist = vectlg + vTotalDistance[i];
  33459. vTotalDistance[i] = dist;
  33460. }
  33461. }
  33462. // uvs
  33463. var u;
  33464. var v;
  33465. if (customUV) {
  33466. for (p = 0; p < customUV.length; p++) {
  33467. uvs.push(customUV[p].x, customUV[p].y);
  33468. }
  33469. }
  33470. else {
  33471. for (p = 0; p < pathArray.length; p++) {
  33472. for (i = 0; i < minlg + closePathCorr; i++) {
  33473. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33474. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33475. if (invertUV) {
  33476. uvs.push(v, u);
  33477. }
  33478. else {
  33479. uvs.push(u, v);
  33480. }
  33481. }
  33482. }
  33483. }
  33484. // indices
  33485. p = 0; // path index
  33486. var pi = 0; // positions array index
  33487. var l1 = lg[p] - 1; // path1 length
  33488. var l2 = lg[p + 1] - 1; // path2 length
  33489. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33490. var shft = idx[1] - idx[0]; // shift
  33491. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33492. while (pi <= min && p < path1nb) {
  33493. // 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
  33494. indices.push(pi, pi + shft, pi + 1);
  33495. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33496. pi += 1;
  33497. if (pi === min) {
  33498. p++;
  33499. if (p === lg.length - 1) {
  33500. shft = idx[0] - idx[p];
  33501. l1 = lg[p] - 1;
  33502. l2 = lg[0] - 1;
  33503. }
  33504. else {
  33505. shft = idx[p + 1] - idx[p];
  33506. l1 = lg[p] - 1;
  33507. l2 = lg[p + 1] - 1;
  33508. }
  33509. pi = idx[p];
  33510. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33511. }
  33512. }
  33513. // normals
  33514. VertexData.ComputeNormals(positions, indices, normals);
  33515. if (closePath) {
  33516. var indexFirst = 0;
  33517. var indexLast = 0;
  33518. for (p = 0; p < pathArray.length; p++) {
  33519. indexFirst = idx[p] * 3;
  33520. if (p + 1 < pathArray.length) {
  33521. indexLast = (idx[p + 1] - 1) * 3;
  33522. }
  33523. else {
  33524. indexLast = normals.length - 3;
  33525. }
  33526. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33527. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33528. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33529. normals[indexLast] = normals[indexFirst];
  33530. normals[indexLast + 1] = normals[indexFirst + 1];
  33531. normals[indexLast + 2] = normals[indexFirst + 2];
  33532. }
  33533. }
  33534. // sides
  33535. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33536. // Colors
  33537. var colors = null;
  33538. if (customColors) {
  33539. colors = new Float32Array(customColors.length * 4);
  33540. for (var c = 0; c < customColors.length; c++) {
  33541. colors[c * 4] = customColors[c].r;
  33542. colors[c * 4 + 1] = customColors[c].g;
  33543. colors[c * 4 + 2] = customColors[c].b;
  33544. colors[c * 4 + 3] = customColors[c].a;
  33545. }
  33546. }
  33547. // Result
  33548. var vertexData = new VertexData();
  33549. var positions32 = new Float32Array(positions);
  33550. var normals32 = new Float32Array(normals);
  33551. var uvs32 = new Float32Array(uvs);
  33552. vertexData.indices = indices;
  33553. vertexData.positions = positions32;
  33554. vertexData.normals = normals32;
  33555. vertexData.uvs = uvs32;
  33556. if (colors) {
  33557. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33558. }
  33559. if (closePath) {
  33560. vertexData._idx = idx;
  33561. }
  33562. return vertexData;
  33563. };
  33564. /**
  33565. * Creates the VertexData of the Box.
  33566. */
  33567. VertexData.CreateBox = function (options) {
  33568. var normalsSource = [
  33569. new BABYLON.Vector3(0, 0, 1),
  33570. new BABYLON.Vector3(0, 0, -1),
  33571. new BABYLON.Vector3(1, 0, 0),
  33572. new BABYLON.Vector3(-1, 0, 0),
  33573. new BABYLON.Vector3(0, 1, 0),
  33574. new BABYLON.Vector3(0, -1, 0)
  33575. ];
  33576. var indices = [];
  33577. var positions = [];
  33578. var normals = [];
  33579. var uvs = [];
  33580. var width = options.width || options.size || 1;
  33581. var height = options.height || options.size || 1;
  33582. var depth = options.depth || options.size || 1;
  33583. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33584. var faceUV = options.faceUV || new Array(6);
  33585. var faceColors = options.faceColors;
  33586. var colors = [];
  33587. // default face colors and UV if undefined
  33588. for (var f = 0; f < 6; f++) {
  33589. if (faceUV[f] === undefined) {
  33590. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33591. }
  33592. if (faceColors && faceColors[f] === undefined) {
  33593. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33594. }
  33595. }
  33596. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33597. // Create each face in turn.
  33598. for (var index = 0; index < normalsSource.length; index++) {
  33599. var normal = normalsSource[index];
  33600. // Get two vectors perpendicular to the face normal and to each other.
  33601. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33602. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33603. // Six indices (two triangles) per face.
  33604. var verticesLength = positions.length / 3;
  33605. indices.push(verticesLength);
  33606. indices.push(verticesLength + 1);
  33607. indices.push(verticesLength + 2);
  33608. indices.push(verticesLength);
  33609. indices.push(verticesLength + 2);
  33610. indices.push(verticesLength + 3);
  33611. // Four vertices per face.
  33612. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33613. positions.push(vertex.x, vertex.y, vertex.z);
  33614. normals.push(normal.x, normal.y, normal.z);
  33615. uvs.push(faceUV[index].z, faceUV[index].w);
  33616. if (faceColors) {
  33617. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33618. }
  33619. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33620. positions.push(vertex.x, vertex.y, vertex.z);
  33621. normals.push(normal.x, normal.y, normal.z);
  33622. uvs.push(faceUV[index].x, faceUV[index].w);
  33623. if (faceColors) {
  33624. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33625. }
  33626. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33627. positions.push(vertex.x, vertex.y, vertex.z);
  33628. normals.push(normal.x, normal.y, normal.z);
  33629. uvs.push(faceUV[index].x, faceUV[index].y);
  33630. if (faceColors) {
  33631. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33632. }
  33633. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33634. positions.push(vertex.x, vertex.y, vertex.z);
  33635. normals.push(normal.x, normal.y, normal.z);
  33636. uvs.push(faceUV[index].z, faceUV[index].y);
  33637. if (faceColors) {
  33638. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33639. }
  33640. }
  33641. // sides
  33642. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33643. // Result
  33644. var vertexData = new VertexData();
  33645. vertexData.indices = indices;
  33646. vertexData.positions = positions;
  33647. vertexData.normals = normals;
  33648. vertexData.uvs = uvs;
  33649. if (faceColors) {
  33650. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33651. vertexData.colors = totalColors;
  33652. }
  33653. return vertexData;
  33654. };
  33655. /**
  33656. * Creates the VertexData of the Sphere.
  33657. */
  33658. VertexData.CreateSphere = function (options) {
  33659. var segments = options.segments || 32;
  33660. var diameterX = options.diameterX || options.diameter || 1;
  33661. var diameterY = options.diameterY || options.diameter || 1;
  33662. var diameterZ = options.diameterZ || options.diameter || 1;
  33663. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33664. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33665. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33666. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33667. var totalZRotationSteps = 2 + segments;
  33668. var totalYRotationSteps = 2 * totalZRotationSteps;
  33669. var indices = [];
  33670. var positions = [];
  33671. var normals = [];
  33672. var uvs = [];
  33673. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33674. var normalizedZ = zRotationStep / totalZRotationSteps;
  33675. var angleZ = normalizedZ * Math.PI * slice;
  33676. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33677. var normalizedY = yRotationStep / totalYRotationSteps;
  33678. var angleY = normalizedY * Math.PI * 2 * arc;
  33679. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33680. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33681. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33682. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33683. var vertex = complete.multiply(radius);
  33684. var normal = complete.divide(radius).normalize();
  33685. positions.push(vertex.x, vertex.y, vertex.z);
  33686. normals.push(normal.x, normal.y, normal.z);
  33687. uvs.push(normalizedY, normalizedZ);
  33688. }
  33689. if (zRotationStep > 0) {
  33690. var verticesCount = positions.length / 3;
  33691. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33692. indices.push((firstIndex));
  33693. indices.push((firstIndex + 1));
  33694. indices.push(firstIndex + totalYRotationSteps + 1);
  33695. indices.push((firstIndex + totalYRotationSteps + 1));
  33696. indices.push((firstIndex + 1));
  33697. indices.push((firstIndex + totalYRotationSteps + 2));
  33698. }
  33699. }
  33700. }
  33701. // Sides
  33702. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33703. // Result
  33704. var vertexData = new VertexData();
  33705. vertexData.indices = indices;
  33706. vertexData.positions = positions;
  33707. vertexData.normals = normals;
  33708. vertexData.uvs = uvs;
  33709. return vertexData;
  33710. };
  33711. /**
  33712. * Creates the VertexData of the Cylinder or Cone.
  33713. */
  33714. VertexData.CreateCylinder = function (options) {
  33715. var height = options.height || 2;
  33716. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33717. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33718. var tessellation = options.tessellation || 24;
  33719. var subdivisions = options.subdivisions || 1;
  33720. var hasRings = options.hasRings ? true : false;
  33721. var enclose = options.enclose ? true : false;
  33722. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33723. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33724. var faceUV = options.faceUV || new Array(3);
  33725. var faceColors = options.faceColors;
  33726. // default face colors and UV if undefined
  33727. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33728. var ringNb = (hasRings) ? subdivisions : 1;
  33729. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33730. var f;
  33731. for (f = 0; f < surfaceNb; f++) {
  33732. if (faceColors && faceColors[f] === undefined) {
  33733. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33734. }
  33735. }
  33736. for (f = 0; f < surfaceNb; f++) {
  33737. if (faceUV && faceUV[f] === undefined) {
  33738. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33739. }
  33740. }
  33741. var indices = new Array();
  33742. var positions = new Array();
  33743. var normals = new Array();
  33744. var uvs = new Array();
  33745. var colors = new Array();
  33746. var angle_step = Math.PI * 2 * arc / tessellation;
  33747. var angle;
  33748. var h;
  33749. var radius;
  33750. var tan = (diameterBottom - diameterTop) / 2 / height;
  33751. var ringVertex = BABYLON.Vector3.Zero();
  33752. var ringNormal = BABYLON.Vector3.Zero();
  33753. var ringFirstVertex = BABYLON.Vector3.Zero();
  33754. var ringFirstNormal = BABYLON.Vector3.Zero();
  33755. var quadNormal = BABYLON.Vector3.Zero();
  33756. var Y = BABYLON.Axis.Y;
  33757. // positions, normals, uvs
  33758. var i;
  33759. var j;
  33760. var r;
  33761. var ringIdx = 1;
  33762. var s = 1; // surface index
  33763. var cs = 0;
  33764. var v = 0;
  33765. for (i = 0; i <= subdivisions; i++) {
  33766. h = i / subdivisions;
  33767. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33768. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33769. for (r = 0; r < ringIdx; r++) {
  33770. if (hasRings) {
  33771. s += r;
  33772. }
  33773. if (enclose) {
  33774. s += 2 * r;
  33775. }
  33776. for (j = 0; j <= tessellation; j++) {
  33777. angle = j * angle_step;
  33778. // position
  33779. ringVertex.x = Math.cos(-angle) * radius;
  33780. ringVertex.y = -height / 2 + h * height;
  33781. ringVertex.z = Math.sin(-angle) * radius;
  33782. // normal
  33783. if (diameterTop === 0 && i === subdivisions) {
  33784. // if no top cap, reuse former normals
  33785. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33786. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33787. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33788. }
  33789. else {
  33790. ringNormal.x = ringVertex.x;
  33791. ringNormal.z = ringVertex.z;
  33792. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33793. ringNormal.normalize();
  33794. }
  33795. // keep first ring vertex values for enclose
  33796. if (j === 0) {
  33797. ringFirstVertex.copyFrom(ringVertex);
  33798. ringFirstNormal.copyFrom(ringNormal);
  33799. }
  33800. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33801. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33802. if (hasRings) {
  33803. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33804. }
  33805. else {
  33806. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33807. }
  33808. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33809. if (faceColors) {
  33810. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33811. }
  33812. }
  33813. // if enclose, add four vertices and their dedicated normals
  33814. if (arc !== 1 && enclose) {
  33815. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33816. positions.push(0, ringVertex.y, 0);
  33817. positions.push(0, ringVertex.y, 0);
  33818. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33819. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33820. quadNormal.normalize();
  33821. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33822. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33823. quadNormal.normalize();
  33824. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33825. if (hasRings) {
  33826. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33827. }
  33828. else {
  33829. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33830. }
  33831. uvs.push(faceUV[s + 1].x, v);
  33832. uvs.push(faceUV[s + 1].z, v);
  33833. if (hasRings) {
  33834. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33835. }
  33836. else {
  33837. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33838. }
  33839. uvs.push(faceUV[s + 2].x, v);
  33840. uvs.push(faceUV[s + 2].z, v);
  33841. if (faceColors) {
  33842. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33843. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33844. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33845. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33846. }
  33847. }
  33848. if (cs !== s) {
  33849. cs = s;
  33850. }
  33851. }
  33852. }
  33853. // indices
  33854. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33855. var s;
  33856. i = 0;
  33857. for (s = 0; s < subdivisions; s++) {
  33858. var i0 = 0;
  33859. var i1 = 0;
  33860. var i2 = 0;
  33861. var i3 = 0;
  33862. for (j = 0; j < tessellation; j++) {
  33863. i0 = i * (e + 1) + j;
  33864. i1 = (i + 1) * (e + 1) + j;
  33865. i2 = i * (e + 1) + (j + 1);
  33866. i3 = (i + 1) * (e + 1) + (j + 1);
  33867. indices.push(i0, i1, i2);
  33868. indices.push(i3, i2, i1);
  33869. }
  33870. if (arc !== 1 && enclose) {
  33871. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33872. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33873. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33874. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33875. }
  33876. i = (hasRings) ? (i + 2) : (i + 1);
  33877. }
  33878. // Caps
  33879. var createCylinderCap = function (isTop) {
  33880. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33881. if (radius === 0) {
  33882. return;
  33883. }
  33884. // Cap positions, normals & uvs
  33885. var angle;
  33886. var circleVector;
  33887. var i;
  33888. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33889. var c = null;
  33890. if (faceColors) {
  33891. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33892. }
  33893. // cap center
  33894. var vbase = positions.length / 3;
  33895. var offset = isTop ? height / 2 : -height / 2;
  33896. var center = new BABYLON.Vector3(0, offset, 0);
  33897. positions.push(center.x, center.y, center.z);
  33898. normals.push(0, isTop ? 1 : -1, 0);
  33899. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33900. if (c) {
  33901. colors.push(c.r, c.g, c.b, c.a);
  33902. }
  33903. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33904. for (i = 0; i <= tessellation; i++) {
  33905. angle = Math.PI * 2 * i * arc / tessellation;
  33906. var cos = Math.cos(-angle);
  33907. var sin = Math.sin(-angle);
  33908. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33909. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33910. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33911. normals.push(0, isTop ? 1 : -1, 0);
  33912. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33913. if (c) {
  33914. colors.push(c.r, c.g, c.b, c.a);
  33915. }
  33916. }
  33917. // Cap indices
  33918. for (i = 0; i < tessellation; i++) {
  33919. if (!isTop) {
  33920. indices.push(vbase);
  33921. indices.push(vbase + (i + 1));
  33922. indices.push(vbase + (i + 2));
  33923. }
  33924. else {
  33925. indices.push(vbase);
  33926. indices.push(vbase + (i + 2));
  33927. indices.push(vbase + (i + 1));
  33928. }
  33929. }
  33930. };
  33931. // add caps to geometry
  33932. createCylinderCap(false);
  33933. createCylinderCap(true);
  33934. // Sides
  33935. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33936. var vertexData = new VertexData();
  33937. vertexData.indices = indices;
  33938. vertexData.positions = positions;
  33939. vertexData.normals = normals;
  33940. vertexData.uvs = uvs;
  33941. if (faceColors) {
  33942. vertexData.colors = colors;
  33943. }
  33944. return vertexData;
  33945. };
  33946. /**
  33947. * Creates the VertexData of the Torus.
  33948. */
  33949. VertexData.CreateTorus = function (options) {
  33950. var indices = [];
  33951. var positions = [];
  33952. var normals = [];
  33953. var uvs = [];
  33954. var diameter = options.diameter || 1;
  33955. var thickness = options.thickness || 0.5;
  33956. var tessellation = options.tessellation || 16;
  33957. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33958. var stride = tessellation + 1;
  33959. for (var i = 0; i <= tessellation; i++) {
  33960. var u = i / tessellation;
  33961. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33962. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33963. for (var j = 0; j <= tessellation; j++) {
  33964. var v = 1 - j / tessellation;
  33965. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33966. var dx = Math.cos(innerAngle);
  33967. var dy = Math.sin(innerAngle);
  33968. // Create a vertex.
  33969. var normal = new BABYLON.Vector3(dx, dy, 0);
  33970. var position = normal.scale(thickness / 2);
  33971. var textureCoordinate = new BABYLON.Vector2(u, v);
  33972. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33973. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33974. positions.push(position.x, position.y, position.z);
  33975. normals.push(normal.x, normal.y, normal.z);
  33976. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33977. // And create indices for two triangles.
  33978. var nextI = (i + 1) % stride;
  33979. var nextJ = (j + 1) % stride;
  33980. indices.push(i * stride + j);
  33981. indices.push(i * stride + nextJ);
  33982. indices.push(nextI * stride + j);
  33983. indices.push(i * stride + nextJ);
  33984. indices.push(nextI * stride + nextJ);
  33985. indices.push(nextI * stride + j);
  33986. }
  33987. }
  33988. // Sides
  33989. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33990. // Result
  33991. var vertexData = new VertexData();
  33992. vertexData.indices = indices;
  33993. vertexData.positions = positions;
  33994. vertexData.normals = normals;
  33995. vertexData.uvs = uvs;
  33996. return vertexData;
  33997. };
  33998. /**
  33999. * Creates the VertexData of the LineSystem.
  34000. */
  34001. VertexData.CreateLineSystem = function (options) {
  34002. var indices = [];
  34003. var positions = [];
  34004. var lines = options.lines;
  34005. var colors = options.colors;
  34006. var vertexColors = [];
  34007. var idx = 0;
  34008. for (var l = 0; l < lines.length; l++) {
  34009. var points = lines[l];
  34010. for (var index = 0; index < points.length; index++) {
  34011. positions.push(points[index].x, points[index].y, points[index].z);
  34012. if (colors) {
  34013. var color = colors[l];
  34014. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34015. }
  34016. if (index > 0) {
  34017. indices.push(idx - 1);
  34018. indices.push(idx);
  34019. }
  34020. idx++;
  34021. }
  34022. }
  34023. var vertexData = new VertexData();
  34024. vertexData.indices = indices;
  34025. vertexData.positions = positions;
  34026. if (colors) {
  34027. vertexData.colors = vertexColors;
  34028. }
  34029. return vertexData;
  34030. };
  34031. /**
  34032. * Create the VertexData of the DashedLines.
  34033. */
  34034. VertexData.CreateDashedLines = function (options) {
  34035. var dashSize = options.dashSize || 3;
  34036. var gapSize = options.gapSize || 1;
  34037. var dashNb = options.dashNb || 200;
  34038. var points = options.points;
  34039. var positions = new Array();
  34040. var indices = new Array();
  34041. var curvect = BABYLON.Vector3.Zero();
  34042. var lg = 0;
  34043. var nb = 0;
  34044. var shft = 0;
  34045. var dashshft = 0;
  34046. var curshft = 0;
  34047. var idx = 0;
  34048. var i = 0;
  34049. for (i = 0; i < points.length - 1; i++) {
  34050. points[i + 1].subtractToRef(points[i], curvect);
  34051. lg += curvect.length();
  34052. }
  34053. shft = lg / dashNb;
  34054. dashshft = dashSize * shft / (dashSize + gapSize);
  34055. for (i = 0; i < points.length - 1; i++) {
  34056. points[i + 1].subtractToRef(points[i], curvect);
  34057. nb = Math.floor(curvect.length() / shft);
  34058. curvect.normalize();
  34059. for (var j = 0; j < nb; j++) {
  34060. curshft = shft * j;
  34061. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34062. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34063. indices.push(idx, idx + 1);
  34064. idx += 2;
  34065. }
  34066. }
  34067. // Result
  34068. var vertexData = new VertexData();
  34069. vertexData.positions = positions;
  34070. vertexData.indices = indices;
  34071. return vertexData;
  34072. };
  34073. /**
  34074. * Creates the VertexData of the Ground.
  34075. */
  34076. VertexData.CreateGround = function (options) {
  34077. var indices = [];
  34078. var positions = [];
  34079. var normals = [];
  34080. var uvs = [];
  34081. var row, col;
  34082. var width = options.width || 1;
  34083. var height = options.height || 1;
  34084. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34085. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34086. for (row = 0; row <= subdivisionsY; row++) {
  34087. for (col = 0; col <= subdivisionsX; col++) {
  34088. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34089. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34090. positions.push(position.x, position.y, position.z);
  34091. normals.push(normal.x, normal.y, normal.z);
  34092. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34093. }
  34094. }
  34095. for (row = 0; row < subdivisionsY; row++) {
  34096. for (col = 0; col < subdivisionsX; col++) {
  34097. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34098. indices.push(col + 1 + row * (subdivisionsX + 1));
  34099. indices.push(col + row * (subdivisionsX + 1));
  34100. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34101. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34102. indices.push(col + row * (subdivisionsX + 1));
  34103. }
  34104. }
  34105. // Result
  34106. var vertexData = new VertexData();
  34107. vertexData.indices = indices;
  34108. vertexData.positions = positions;
  34109. vertexData.normals = normals;
  34110. vertexData.uvs = uvs;
  34111. return vertexData;
  34112. };
  34113. /**
  34114. * Creates the VertexData of the TiledGround.
  34115. */
  34116. VertexData.CreateTiledGround = function (options) {
  34117. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34118. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34119. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34120. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34121. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34122. var precision = options.precision || { w: 1, h: 1 };
  34123. var indices = new Array();
  34124. var positions = new Array();
  34125. var normals = new Array();
  34126. var uvs = new Array();
  34127. var row, col, tileRow, tileCol;
  34128. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34129. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34130. precision.w = (precision.w < 1) ? 1 : precision.w;
  34131. precision.h = (precision.h < 1) ? 1 : precision.h;
  34132. var tileSize = {
  34133. 'w': (xmax - xmin) / subdivisions.w,
  34134. 'h': (zmax - zmin) / subdivisions.h
  34135. };
  34136. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34137. // Indices
  34138. var base = positions.length / 3;
  34139. var rowLength = precision.w + 1;
  34140. for (row = 0; row < precision.h; row++) {
  34141. for (col = 0; col < precision.w; col++) {
  34142. var square = [
  34143. base + col + row * rowLength,
  34144. base + (col + 1) + row * rowLength,
  34145. base + (col + 1) + (row + 1) * rowLength,
  34146. base + col + (row + 1) * rowLength
  34147. ];
  34148. indices.push(square[1]);
  34149. indices.push(square[2]);
  34150. indices.push(square[3]);
  34151. indices.push(square[0]);
  34152. indices.push(square[1]);
  34153. indices.push(square[3]);
  34154. }
  34155. }
  34156. // Position, normals and uvs
  34157. var position = BABYLON.Vector3.Zero();
  34158. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34159. for (row = 0; row <= precision.h; row++) {
  34160. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34161. for (col = 0; col <= precision.w; col++) {
  34162. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34163. position.y = 0;
  34164. positions.push(position.x, position.y, position.z);
  34165. normals.push(normal.x, normal.y, normal.z);
  34166. uvs.push(col / precision.w, row / precision.h);
  34167. }
  34168. }
  34169. }
  34170. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34171. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34172. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34173. }
  34174. }
  34175. // Result
  34176. var vertexData = new VertexData();
  34177. vertexData.indices = indices;
  34178. vertexData.positions = positions;
  34179. vertexData.normals = normals;
  34180. vertexData.uvs = uvs;
  34181. return vertexData;
  34182. };
  34183. /**
  34184. * Creates the VertexData of the Ground designed from a heightmap.
  34185. */
  34186. VertexData.CreateGroundFromHeightMap = function (options) {
  34187. var indices = [];
  34188. var positions = [];
  34189. var normals = [];
  34190. var uvs = [];
  34191. var row, col;
  34192. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34193. // Vertices
  34194. for (row = 0; row <= options.subdivisions; row++) {
  34195. for (col = 0; col <= options.subdivisions; col++) {
  34196. 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));
  34197. // Compute height
  34198. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34199. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34200. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34201. var r = options.buffer[pos] / 255.0;
  34202. var g = options.buffer[pos + 1] / 255.0;
  34203. var b = options.buffer[pos + 2] / 255.0;
  34204. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34205. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34206. // Add vertex
  34207. positions.push(position.x, position.y, position.z);
  34208. normals.push(0, 0, 0);
  34209. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34210. }
  34211. }
  34212. // Indices
  34213. for (row = 0; row < options.subdivisions; row++) {
  34214. for (col = 0; col < options.subdivisions; col++) {
  34215. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34216. indices.push(col + 1 + row * (options.subdivisions + 1));
  34217. indices.push(col + row * (options.subdivisions + 1));
  34218. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34219. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34220. indices.push(col + row * (options.subdivisions + 1));
  34221. }
  34222. }
  34223. // Normals
  34224. VertexData.ComputeNormals(positions, indices, normals);
  34225. // Result
  34226. var vertexData = new VertexData();
  34227. vertexData.indices = indices;
  34228. vertexData.positions = positions;
  34229. vertexData.normals = normals;
  34230. vertexData.uvs = uvs;
  34231. return vertexData;
  34232. };
  34233. /**
  34234. * Creates the VertexData of the Plane.
  34235. */
  34236. VertexData.CreatePlane = function (options) {
  34237. var indices = [];
  34238. var positions = [];
  34239. var normals = [];
  34240. var uvs = [];
  34241. var width = options.width || options.size || 1;
  34242. var height = options.height || options.size || 1;
  34243. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34244. // Vertices
  34245. var halfWidth = width / 2.0;
  34246. var halfHeight = height / 2.0;
  34247. positions.push(-halfWidth, -halfHeight, 0);
  34248. normals.push(0, 0, -1.0);
  34249. uvs.push(0.0, 0.0);
  34250. positions.push(halfWidth, -halfHeight, 0);
  34251. normals.push(0, 0, -1.0);
  34252. uvs.push(1.0, 0.0);
  34253. positions.push(halfWidth, halfHeight, 0);
  34254. normals.push(0, 0, -1.0);
  34255. uvs.push(1.0, 1.0);
  34256. positions.push(-halfWidth, halfHeight, 0);
  34257. normals.push(0, 0, -1.0);
  34258. uvs.push(0.0, 1.0);
  34259. // Indices
  34260. indices.push(0);
  34261. indices.push(1);
  34262. indices.push(2);
  34263. indices.push(0);
  34264. indices.push(2);
  34265. indices.push(3);
  34266. // Sides
  34267. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34268. // Result
  34269. var vertexData = new VertexData();
  34270. vertexData.indices = indices;
  34271. vertexData.positions = positions;
  34272. vertexData.normals = normals;
  34273. vertexData.uvs = uvs;
  34274. return vertexData;
  34275. };
  34276. /**
  34277. * Creates the VertexData of the Disc or regular Polygon.
  34278. */
  34279. VertexData.CreateDisc = function (options) {
  34280. var positions = new Array();
  34281. var indices = new Array();
  34282. var normals = new Array();
  34283. var uvs = new Array();
  34284. var radius = options.radius || 0.5;
  34285. var tessellation = options.tessellation || 64;
  34286. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34287. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34288. // positions and uvs
  34289. positions.push(0, 0, 0); // disc center first
  34290. uvs.push(0.5, 0.5);
  34291. var theta = Math.PI * 2 * arc;
  34292. var step = theta / tessellation;
  34293. for (var a = 0; a < theta; a += step) {
  34294. var x = Math.cos(a);
  34295. var y = Math.sin(a);
  34296. var u = (x + 1) / 2;
  34297. var v = (1 - y) / 2;
  34298. positions.push(radius * x, radius * y, 0);
  34299. uvs.push(u, v);
  34300. }
  34301. if (arc === 1) {
  34302. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34303. uvs.push(uvs[2], uvs[3]);
  34304. }
  34305. //indices
  34306. var vertexNb = positions.length / 3;
  34307. for (var i = 1; i < vertexNb - 1; i++) {
  34308. indices.push(i + 1, 0, i);
  34309. }
  34310. // result
  34311. VertexData.ComputeNormals(positions, indices, normals);
  34312. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34313. var vertexData = new VertexData();
  34314. vertexData.indices = indices;
  34315. vertexData.positions = positions;
  34316. vertexData.normals = normals;
  34317. vertexData.uvs = uvs;
  34318. return vertexData;
  34319. };
  34320. /**
  34321. * Re-creates the VertexData of the Polygon for sideOrientation.
  34322. */
  34323. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34324. var faceUV = fUV || new Array(3);
  34325. var faceColors = fColors;
  34326. var colors = [];
  34327. // default face colors and UV if undefined
  34328. for (var f = 0; f < 3; f++) {
  34329. if (faceUV[f] === undefined) {
  34330. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34331. }
  34332. if (faceColors && faceColors[f] === undefined) {
  34333. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34334. }
  34335. }
  34336. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34337. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34338. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34339. var indices = polygon.getIndices();
  34340. // set face colours and textures
  34341. var idx = 0;
  34342. var face = 0;
  34343. for (var index = 0; index < normals.length; index += 3) {
  34344. //Edge Face no. 1
  34345. if (Math.abs(normals[index + 1]) < 0.001) {
  34346. face = 1;
  34347. }
  34348. //Top Face no. 0
  34349. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34350. face = 0;
  34351. }
  34352. //Bottom Face no. 2
  34353. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34354. face = 2;
  34355. }
  34356. idx = index / 3;
  34357. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34358. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34359. if (faceColors) {
  34360. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34361. }
  34362. }
  34363. // sides
  34364. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34365. // Result
  34366. var vertexData = new VertexData();
  34367. vertexData.indices = indices;
  34368. vertexData.positions = positions;
  34369. vertexData.normals = normals;
  34370. vertexData.uvs = uvs;
  34371. if (faceColors) {
  34372. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34373. vertexData.colors = totalColors;
  34374. }
  34375. return vertexData;
  34376. };
  34377. /**
  34378. * Creates the VertexData of the IcoSphere.
  34379. */
  34380. VertexData.CreateIcoSphere = function (options) {
  34381. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34382. var radius = options.radius || 1;
  34383. var flat = (options.flat === undefined) ? true : options.flat;
  34384. var subdivisions = options.subdivisions || 4;
  34385. var radiusX = options.radiusX || radius;
  34386. var radiusY = options.radiusY || radius;
  34387. var radiusZ = options.radiusZ || radius;
  34388. var t = (1 + Math.sqrt(5)) / 2;
  34389. // 12 vertex x,y,z
  34390. var ico_vertices = [
  34391. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34392. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34393. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34394. ];
  34395. // index of 3 vertex makes a face of icopshere
  34396. var ico_indices = [
  34397. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34398. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34399. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34400. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34401. ];
  34402. // vertex for uv have aliased position, not for UV
  34403. var vertices_unalias_id = [
  34404. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34405. // vertex alias
  34406. 0,
  34407. 2,
  34408. 3,
  34409. 3,
  34410. 3,
  34411. 4,
  34412. 7,
  34413. 8,
  34414. 9,
  34415. 9,
  34416. 10,
  34417. 11 // 23: B + 12
  34418. ];
  34419. // uv as integer step (not pixels !)
  34420. var ico_vertexuv = [
  34421. 5, 1, 3, 1, 6, 4, 0, 0,
  34422. 5, 3, 4, 2, 2, 2, 4, 0,
  34423. 2, 0, 1, 1, 6, 0, 6, 2,
  34424. // vertex alias (for same vertex on different faces)
  34425. 0, 4,
  34426. 3, 3,
  34427. 4, 4,
  34428. 3, 1,
  34429. 4, 2,
  34430. 4, 4,
  34431. 0, 2,
  34432. 1, 1,
  34433. 2, 2,
  34434. 3, 3,
  34435. 1, 3,
  34436. 2, 4 // 23: B + 12
  34437. ];
  34438. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34439. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34440. // First island of uv mapping
  34441. // v = 4h 3+ 2
  34442. // v = 3h 9+ 4
  34443. // v = 2h 9+ 5 B
  34444. // v = 1h 9 1 0
  34445. // v = 0h 3 8 7 A
  34446. // u = 0 1 2 3 4 5 6 *a
  34447. // Second island of uv mapping
  34448. // v = 4h 0+ B+ 4+
  34449. // v = 3h A+ 2+
  34450. // v = 2h 7+ 6 3+
  34451. // v = 1h 8+ 3+
  34452. // v = 0h
  34453. // u = 0 1 2 3 4 5 6 *a
  34454. // Face layout on texture UV mapping
  34455. // ============
  34456. // \ 4 /\ 16 / ======
  34457. // \ / \ / /\ 11 /
  34458. // \/ 7 \/ / \ /
  34459. // ======= / 10 \/
  34460. // /\ 17 /\ =======
  34461. // / \ / \ \ 15 /\
  34462. // / 8 \/ 12 \ \ / \
  34463. // ============ \/ 6 \
  34464. // \ 18 /\ ============
  34465. // \ / \ \ 5 /\ 0 /
  34466. // \/ 13 \ \ / \ /
  34467. // ======= \/ 1 \/
  34468. // =============
  34469. // /\ 19 /\ 2 /\
  34470. // / \ / \ / \
  34471. // / 14 \/ 9 \/ 3 \
  34472. // ===================
  34473. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34474. var ustep = 138 / 1024;
  34475. var vstep = 239 / 1024;
  34476. var uoffset = 60 / 1024;
  34477. var voffset = 26 / 1024;
  34478. // Second island should have margin, not to touch the first island
  34479. // avoid any borderline artefact in pixel rounding
  34480. var island_u_offset = -40 / 1024;
  34481. var island_v_offset = +20 / 1024;
  34482. // face is either island 0 or 1 :
  34483. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34484. var island = [
  34485. 0, 0, 0, 0, 1,
  34486. 0, 0, 1, 1, 0,
  34487. 0, 0, 1, 1, 0,
  34488. 0, 1, 1, 1, 0 // 15 - 19
  34489. ];
  34490. var indices = new Array();
  34491. var positions = new Array();
  34492. var normals = new Array();
  34493. var uvs = new Array();
  34494. var current_indice = 0;
  34495. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34496. var face_vertex_pos = new Array(3);
  34497. var face_vertex_uv = new Array(3);
  34498. var v012;
  34499. for (v012 = 0; v012 < 3; v012++) {
  34500. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34501. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34502. }
  34503. // create all with normals
  34504. for (var face = 0; face < 20; face++) {
  34505. // 3 vertex per face
  34506. for (v012 = 0; v012 < 3; v012++) {
  34507. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34508. var v_id = ico_indices[3 * face + v012];
  34509. // vertex have 3D position (x,y,z)
  34510. 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]);
  34511. // Normalize to get normal, then scale to radius
  34512. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34513. // uv Coordinates from vertex ID
  34514. 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);
  34515. }
  34516. // Subdivide the face (interpolate pos, norm, uv)
  34517. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34518. // - norm is linear interpolation of vertex corner normal
  34519. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34520. // - uv is linear interpolation
  34521. //
  34522. // Topology is as below for sub-divide by 2
  34523. // vertex shown as v0,v1,v2
  34524. // interp index is i1 to progress in range [v0,v1[
  34525. // interp index is i2 to progress in range [v0,v2[
  34526. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34527. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34528. //
  34529. //
  34530. // i2 v2
  34531. // ^ ^
  34532. // / / \
  34533. // / / \
  34534. // / / \
  34535. // / / (0,1) \
  34536. // / #---------\
  34537. // / / \ (0,0)'/ \
  34538. // / / \ / \
  34539. // / / \ / \
  34540. // / / (0,0) \ / (1,0) \
  34541. // / #---------#---------\
  34542. // v0 v1
  34543. //
  34544. // --------------------> i1
  34545. //
  34546. // interp of (i1,i2):
  34547. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34548. // along i1 : lerp(x0,x1, i1/(S-i2))
  34549. //
  34550. // centroid of triangle is needed to get help normal computation
  34551. // (c1,c2) are used for centroid location
  34552. var interp_vertex = function (i1, i2, c1, c2) {
  34553. // vertex is interpolated from
  34554. // - face_vertex_pos[0..2]
  34555. // - face_vertex_uv[0..2]
  34556. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34557. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34558. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34559. pos_interp.normalize();
  34560. var vertex_normal;
  34561. if (flat) {
  34562. // in flat mode, recalculate normal as face centroid normal
  34563. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34564. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34565. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34566. }
  34567. else {
  34568. // in smooth mode, recalculate normal from each single vertex position
  34569. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34570. }
  34571. // Vertex normal need correction due to X,Y,Z radius scaling
  34572. vertex_normal.x /= radiusX;
  34573. vertex_normal.y /= radiusY;
  34574. vertex_normal.z /= radiusZ;
  34575. vertex_normal.normalize();
  34576. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34577. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34578. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34579. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34580. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34581. uvs.push(uv_interp.x, uv_interp.y);
  34582. // push each vertex has member of a face
  34583. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34584. indices.push(current_indice);
  34585. current_indice++;
  34586. };
  34587. for (var i2 = 0; i2 < subdivisions; i2++) {
  34588. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34589. // face : (i1,i2) for /\ :
  34590. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34591. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34592. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34593. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34594. if (i1 + i2 + 1 < subdivisions) {
  34595. // face : (i1,i2)' for \/ :
  34596. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34597. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34598. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34599. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34600. }
  34601. }
  34602. }
  34603. }
  34604. // Sides
  34605. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34606. // Result
  34607. var vertexData = new VertexData();
  34608. vertexData.indices = indices;
  34609. vertexData.positions = positions;
  34610. vertexData.normals = normals;
  34611. vertexData.uvs = uvs;
  34612. return vertexData;
  34613. };
  34614. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34615. /**
  34616. * Creates the VertexData of the Polyhedron.
  34617. */
  34618. VertexData.CreatePolyhedron = function (options) {
  34619. // provided polyhedron types :
  34620. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34621. // 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)
  34622. var polyhedra = [];
  34623. 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]] };
  34624. 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]] };
  34625. polyhedra[2] = {
  34626. 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]],
  34627. 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]]
  34628. };
  34629. polyhedra[3] = {
  34630. 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]],
  34631. 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]]
  34632. };
  34633. polyhedra[4] = {
  34634. 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]],
  34635. 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]]
  34636. };
  34637. 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]] };
  34638. 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]] };
  34639. 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]] };
  34640. 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]] };
  34641. 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]] };
  34642. 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]] };
  34643. 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]] };
  34644. 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]] };
  34645. 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]] };
  34646. polyhedra[14] = {
  34647. 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]],
  34648. 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]]
  34649. };
  34650. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34651. var size = options.size;
  34652. var sizeX = options.sizeX || size || 1;
  34653. var sizeY = options.sizeY || size || 1;
  34654. var sizeZ = options.sizeZ || size || 1;
  34655. var data = options.custom || polyhedra[type];
  34656. var nbfaces = data.face.length;
  34657. var faceUV = options.faceUV || new Array(nbfaces);
  34658. var faceColors = options.faceColors;
  34659. var flat = (options.flat === undefined) ? true : options.flat;
  34660. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34661. var positions = new Array();
  34662. var indices = new Array();
  34663. var normals = new Array();
  34664. var uvs = new Array();
  34665. var colors = new Array();
  34666. var index = 0;
  34667. var faceIdx = 0; // face cursor in the array "indexes"
  34668. var indexes = new Array();
  34669. var i = 0;
  34670. var f = 0;
  34671. var u, v, ang, x, y, tmp;
  34672. // default face colors and UV if undefined
  34673. if (flat) {
  34674. for (f = 0; f < nbfaces; f++) {
  34675. if (faceColors && faceColors[f] === undefined) {
  34676. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34677. }
  34678. if (faceUV && faceUV[f] === undefined) {
  34679. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34680. }
  34681. }
  34682. }
  34683. if (!flat) {
  34684. for (i = 0; i < data.vertex.length; i++) {
  34685. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34686. uvs.push(0, 0);
  34687. }
  34688. for (f = 0; f < nbfaces; f++) {
  34689. for (i = 0; i < data.face[f].length - 2; i++) {
  34690. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34691. }
  34692. }
  34693. }
  34694. else {
  34695. for (f = 0; f < nbfaces; f++) {
  34696. var fl = data.face[f].length; // number of vertices of the current face
  34697. ang = 2 * Math.PI / fl;
  34698. x = 0.5 * Math.tan(ang / 2);
  34699. y = 0.5;
  34700. // positions, uvs, colors
  34701. for (i = 0; i < fl; i++) {
  34702. // positions
  34703. 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);
  34704. indexes.push(index);
  34705. index++;
  34706. // uvs
  34707. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34708. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34709. uvs.push(u, v);
  34710. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34711. y = x * Math.sin(ang) + y * Math.cos(ang);
  34712. x = tmp;
  34713. // colors
  34714. if (faceColors) {
  34715. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34716. }
  34717. }
  34718. // indices from indexes
  34719. for (i = 0; i < fl - 2; i++) {
  34720. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34721. }
  34722. faceIdx += fl;
  34723. }
  34724. }
  34725. VertexData.ComputeNormals(positions, indices, normals);
  34726. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34727. var vertexData = new VertexData();
  34728. vertexData.positions = positions;
  34729. vertexData.indices = indices;
  34730. vertexData.normals = normals;
  34731. vertexData.uvs = uvs;
  34732. if (faceColors && flat) {
  34733. vertexData.colors = colors;
  34734. }
  34735. return vertexData;
  34736. };
  34737. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34738. /**
  34739. * Creates the VertexData of the Torus Knot.
  34740. */
  34741. VertexData.CreateTorusKnot = function (options) {
  34742. var indices = new Array();
  34743. var positions = new Array();
  34744. var normals = new Array();
  34745. var uvs = new Array();
  34746. var radius = options.radius || 2;
  34747. var tube = options.tube || 0.5;
  34748. var radialSegments = options.radialSegments || 32;
  34749. var tubularSegments = options.tubularSegments || 32;
  34750. var p = options.p || 2;
  34751. var q = options.q || 3;
  34752. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34753. // Helper
  34754. var getPos = function (angle) {
  34755. var cu = Math.cos(angle);
  34756. var su = Math.sin(angle);
  34757. var quOverP = q / p * angle;
  34758. var cs = Math.cos(quOverP);
  34759. var tx = radius * (2 + cs) * 0.5 * cu;
  34760. var ty = radius * (2 + cs) * su * 0.5;
  34761. var tz = radius * Math.sin(quOverP) * 0.5;
  34762. return new BABYLON.Vector3(tx, ty, tz);
  34763. };
  34764. // Vertices
  34765. var i;
  34766. var j;
  34767. for (i = 0; i <= radialSegments; i++) {
  34768. var modI = i % radialSegments;
  34769. var u = modI / radialSegments * 2 * p * Math.PI;
  34770. var p1 = getPos(u);
  34771. var p2 = getPos(u + 0.01);
  34772. var tang = p2.subtract(p1);
  34773. var n = p2.add(p1);
  34774. var bitan = BABYLON.Vector3.Cross(tang, n);
  34775. n = BABYLON.Vector3.Cross(bitan, tang);
  34776. bitan.normalize();
  34777. n.normalize();
  34778. for (j = 0; j < tubularSegments; j++) {
  34779. var modJ = j % tubularSegments;
  34780. var v = modJ / tubularSegments * 2 * Math.PI;
  34781. var cx = -tube * Math.cos(v);
  34782. var cy = tube * Math.sin(v);
  34783. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34784. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34785. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34786. uvs.push(i / radialSegments);
  34787. uvs.push(j / tubularSegments);
  34788. }
  34789. }
  34790. for (i = 0; i < radialSegments; i++) {
  34791. for (j = 0; j < tubularSegments; j++) {
  34792. var jNext = (j + 1) % tubularSegments;
  34793. var a = i * tubularSegments + j;
  34794. var b = (i + 1) * tubularSegments + j;
  34795. var c = (i + 1) * tubularSegments + jNext;
  34796. var d = i * tubularSegments + jNext;
  34797. indices.push(d);
  34798. indices.push(b);
  34799. indices.push(a);
  34800. indices.push(d);
  34801. indices.push(c);
  34802. indices.push(b);
  34803. }
  34804. }
  34805. // Normals
  34806. VertexData.ComputeNormals(positions, indices, normals);
  34807. // Sides
  34808. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34809. // Result
  34810. var vertexData = new VertexData();
  34811. vertexData.indices = indices;
  34812. vertexData.positions = positions;
  34813. vertexData.normals = normals;
  34814. vertexData.uvs = uvs;
  34815. return vertexData;
  34816. };
  34817. // Tools
  34818. /**
  34819. * @param {any} - positions (number[] or Float32Array)
  34820. * @param {any} - indices (number[] or Uint16Array)
  34821. * @param {any} - normals (number[] or Float32Array)
  34822. * options (optional) :
  34823. * facetPositions : optional array of facet positions (vector3)
  34824. * facetNormals : optional array of facet normals (vector3)
  34825. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34826. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34827. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34828. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34829. * bInfo : optional bounding info, required for facetPartitioning computation
  34830. * useRightHandedSystem: optional boolean to for right handed system computation
  34831. * depthSort : optional boolean to enable the facet depth sort computation
  34832. * distanceTo : optional Vector3 to compute the facet depth from this location
  34833. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34834. */
  34835. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34836. // temporary scalar variables
  34837. var index = 0; // facet index
  34838. var p1p2x = 0.0; // p1p2 vector x coordinate
  34839. var p1p2y = 0.0; // p1p2 vector y coordinate
  34840. var p1p2z = 0.0; // p1p2 vector z coordinate
  34841. var p3p2x = 0.0; // p3p2 vector x coordinate
  34842. var p3p2y = 0.0; // p3p2 vector y coordinate
  34843. var p3p2z = 0.0; // p3p2 vector z coordinate
  34844. var faceNormalx = 0.0; // facet normal x coordinate
  34845. var faceNormaly = 0.0; // facet normal y coordinate
  34846. var faceNormalz = 0.0; // facet normal z coordinate
  34847. var length = 0.0; // facet normal length before normalization
  34848. var v1x = 0; // vector1 x index in the positions array
  34849. var v1y = 0; // vector1 y index in the positions array
  34850. var v1z = 0; // vector1 z index in the positions array
  34851. var v2x = 0; // vector2 x index in the positions array
  34852. var v2y = 0; // vector2 y index in the positions array
  34853. var v2z = 0; // vector2 z index in the positions array
  34854. var v3x = 0; // vector3 x index in the positions array
  34855. var v3y = 0; // vector3 y index in the positions array
  34856. var v3z = 0; // vector3 z index in the positions array
  34857. var computeFacetNormals = false;
  34858. var computeFacetPositions = false;
  34859. var computeFacetPartitioning = false;
  34860. var computeDepthSort = false;
  34861. var faceNormalSign = 1;
  34862. var ratio = 0;
  34863. var distanceTo = null;
  34864. if (options) {
  34865. computeFacetNormals = (options.facetNormals) ? true : false;
  34866. computeFacetPositions = (options.facetPositions) ? true : false;
  34867. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34868. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34869. ratio = options.ratio || 0;
  34870. computeDepthSort = (options.depthSort) ? true : false;
  34871. distanceTo = (options.distanceTo);
  34872. if (computeDepthSort) {
  34873. if (distanceTo === undefined) {
  34874. distanceTo = BABYLON.Vector3.Zero();
  34875. }
  34876. var depthSortedFacets = options.depthSortedFacets;
  34877. }
  34878. }
  34879. // facetPartitioning reinit if needed
  34880. var xSubRatio = 0;
  34881. var ySubRatio = 0;
  34882. var zSubRatio = 0;
  34883. var subSq = 0;
  34884. if (computeFacetPartitioning && options && options.bbSize) {
  34885. var ox = 0; // X partitioning index for facet position
  34886. var oy = 0; // Y partinioning index for facet position
  34887. var oz = 0; // Z partinioning index for facet position
  34888. var b1x = 0; // X partitioning index for facet v1 vertex
  34889. var b1y = 0; // Y partitioning index for facet v1 vertex
  34890. var b1z = 0; // z partitioning index for facet v1 vertex
  34891. var b2x = 0; // X partitioning index for facet v2 vertex
  34892. var b2y = 0; // Y partitioning index for facet v2 vertex
  34893. var b2z = 0; // Z partitioning index for facet v2 vertex
  34894. var b3x = 0; // X partitioning index for facet v3 vertex
  34895. var b3y = 0; // Y partitioning index for facet v3 vertex
  34896. var b3z = 0; // Z partitioning index for facet v3 vertex
  34897. var block_idx_o = 0; // facet barycenter block index
  34898. var block_idx_v1 = 0; // v1 vertex block index
  34899. var block_idx_v2 = 0; // v2 vertex block index
  34900. var block_idx_v3 = 0; // v3 vertex block index
  34901. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34902. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34903. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34904. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34905. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34906. subSq = options.subDiv.max * options.subDiv.max;
  34907. options.facetPartitioning.length = 0;
  34908. }
  34909. // reset the normals
  34910. for (index = 0; index < positions.length; index++) {
  34911. normals[index] = 0.0;
  34912. }
  34913. // Loop : 1 indice triplet = 1 facet
  34914. var nbFaces = (indices.length / 3) | 0;
  34915. for (index = 0; index < nbFaces; index++) {
  34916. // get the indexes of the coordinates of each vertex of the facet
  34917. v1x = indices[index * 3] * 3;
  34918. v1y = v1x + 1;
  34919. v1z = v1x + 2;
  34920. v2x = indices[index * 3 + 1] * 3;
  34921. v2y = v2x + 1;
  34922. v2z = v2x + 2;
  34923. v3x = indices[index * 3 + 2] * 3;
  34924. v3y = v3x + 1;
  34925. v3z = v3x + 2;
  34926. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34927. p1p2y = positions[v1y] - positions[v2y];
  34928. p1p2z = positions[v1z] - positions[v2z];
  34929. p3p2x = positions[v3x] - positions[v2x];
  34930. p3p2y = positions[v3y] - positions[v2y];
  34931. p3p2z = positions[v3z] - positions[v2z];
  34932. // compute the face normal with the cross product
  34933. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34934. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34935. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34936. // normalize this normal and store it in the array facetData
  34937. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34938. length = (length === 0) ? 1.0 : length;
  34939. faceNormalx /= length;
  34940. faceNormaly /= length;
  34941. faceNormalz /= length;
  34942. if (computeFacetNormals && options) {
  34943. options.facetNormals[index].x = faceNormalx;
  34944. options.facetNormals[index].y = faceNormaly;
  34945. options.facetNormals[index].z = faceNormalz;
  34946. }
  34947. if (computeFacetPositions && options) {
  34948. // compute and the facet barycenter coordinates in the array facetPositions
  34949. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34950. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34951. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34952. }
  34953. if (computeFacetPartitioning && options) {
  34954. // store the facet indexes in arrays in the main facetPartitioning array :
  34955. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34956. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34957. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34958. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34959. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34960. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34961. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34962. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34963. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34964. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34965. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34966. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34967. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34968. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34969. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34970. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34971. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34972. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34973. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34974. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34975. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34976. // push each facet index in each block containing the vertex
  34977. options.facetPartitioning[block_idx_v1].push(index);
  34978. if (block_idx_v2 != block_idx_v1) {
  34979. options.facetPartitioning[block_idx_v2].push(index);
  34980. }
  34981. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34982. options.facetPartitioning[block_idx_v3].push(index);
  34983. }
  34984. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34985. options.facetPartitioning[block_idx_o].push(index);
  34986. }
  34987. }
  34988. if (computeDepthSort && options && options.facetPositions) {
  34989. var dsf = depthSortedFacets[index];
  34990. dsf.ind = index * 3;
  34991. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34992. }
  34993. // compute the normals anyway
  34994. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34995. normals[v1y] += faceNormaly;
  34996. normals[v1z] += faceNormalz;
  34997. normals[v2x] += faceNormalx;
  34998. normals[v2y] += faceNormaly;
  34999. normals[v2z] += faceNormalz;
  35000. normals[v3x] += faceNormalx;
  35001. normals[v3y] += faceNormaly;
  35002. normals[v3z] += faceNormalz;
  35003. }
  35004. // last normalization of each normal
  35005. for (index = 0; index < normals.length / 3; index++) {
  35006. faceNormalx = normals[index * 3];
  35007. faceNormaly = normals[index * 3 + 1];
  35008. faceNormalz = normals[index * 3 + 2];
  35009. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35010. length = (length === 0) ? 1.0 : length;
  35011. faceNormalx /= length;
  35012. faceNormaly /= length;
  35013. faceNormalz /= length;
  35014. normals[index * 3] = faceNormalx;
  35015. normals[index * 3 + 1] = faceNormaly;
  35016. normals[index * 3 + 2] = faceNormalz;
  35017. }
  35018. };
  35019. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35020. var li = indices.length;
  35021. var ln = normals.length;
  35022. var i;
  35023. var n;
  35024. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35025. switch (sideOrientation) {
  35026. case BABYLON.Mesh.FRONTSIDE:
  35027. // nothing changed
  35028. break;
  35029. case BABYLON.Mesh.BACKSIDE:
  35030. var tmp;
  35031. // indices
  35032. for (i = 0; i < li; i += 3) {
  35033. tmp = indices[i];
  35034. indices[i] = indices[i + 2];
  35035. indices[i + 2] = tmp;
  35036. }
  35037. // normals
  35038. for (n = 0; n < ln; n++) {
  35039. normals[n] = -normals[n];
  35040. }
  35041. break;
  35042. case BABYLON.Mesh.DOUBLESIDE:
  35043. // positions
  35044. var lp = positions.length;
  35045. var l = lp / 3;
  35046. for (var p = 0; p < lp; p++) {
  35047. positions[lp + p] = positions[p];
  35048. }
  35049. // indices
  35050. for (i = 0; i < li; i += 3) {
  35051. indices[i + li] = indices[i + 2] + l;
  35052. indices[i + 1 + li] = indices[i + 1] + l;
  35053. indices[i + 2 + li] = indices[i] + l;
  35054. }
  35055. // normals
  35056. for (n = 0; n < ln; n++) {
  35057. normals[ln + n] = -normals[n];
  35058. }
  35059. // uvs
  35060. var lu = uvs.length;
  35061. var u = 0;
  35062. for (u = 0; u < lu; u++) {
  35063. uvs[u + lu] = uvs[u];
  35064. }
  35065. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35066. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35067. u = 0;
  35068. for (i = 0; i < lu / 2; i++) {
  35069. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35070. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35071. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35072. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35073. u += 2;
  35074. }
  35075. break;
  35076. }
  35077. };
  35078. /**
  35079. * Creates a new VertexData from the imported parameters.
  35080. */
  35081. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35082. var vertexData = new VertexData();
  35083. // positions
  35084. var positions = parsedVertexData.positions;
  35085. if (positions) {
  35086. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35087. }
  35088. // normals
  35089. var normals = parsedVertexData.normals;
  35090. if (normals) {
  35091. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35092. }
  35093. // tangents
  35094. var tangents = parsedVertexData.tangents;
  35095. if (tangents) {
  35096. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35097. }
  35098. // uvs
  35099. var uvs = parsedVertexData.uvs;
  35100. if (uvs) {
  35101. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35102. }
  35103. // uv2s
  35104. var uv2s = parsedVertexData.uv2s;
  35105. if (uv2s) {
  35106. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35107. }
  35108. // uv3s
  35109. var uv3s = parsedVertexData.uv3s;
  35110. if (uv3s) {
  35111. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35112. }
  35113. // uv4s
  35114. var uv4s = parsedVertexData.uv4s;
  35115. if (uv4s) {
  35116. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35117. }
  35118. // uv5s
  35119. var uv5s = parsedVertexData.uv5s;
  35120. if (uv5s) {
  35121. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35122. }
  35123. // uv6s
  35124. var uv6s = parsedVertexData.uv6s;
  35125. if (uv6s) {
  35126. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35127. }
  35128. // colors
  35129. var colors = parsedVertexData.colors;
  35130. if (colors) {
  35131. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35132. }
  35133. // matricesIndices
  35134. var matricesIndices = parsedVertexData.matricesIndices;
  35135. if (matricesIndices) {
  35136. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35137. }
  35138. // matricesWeights
  35139. var matricesWeights = parsedVertexData.matricesWeights;
  35140. if (matricesWeights) {
  35141. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35142. }
  35143. // indices
  35144. var indices = parsedVertexData.indices;
  35145. if (indices) {
  35146. vertexData.indices = indices;
  35147. }
  35148. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35149. };
  35150. return VertexData;
  35151. }());
  35152. BABYLON.VertexData = VertexData;
  35153. })(BABYLON || (BABYLON = {}));
  35154. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35155. "use strict";
  35156. var BABYLON;
  35157. (function (BABYLON) {
  35158. /**
  35159. * Class used to store geometry data (vertex buffers + index buffer)
  35160. */
  35161. var Geometry = /** @class */ (function () {
  35162. /**
  35163. * Creates a new geometry
  35164. * @param id defines the unique ID
  35165. * @param scene defines the hosting scene
  35166. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35167. * @param updatable defines if geometry must be updatable (false by default)
  35168. * @param mesh defines the mesh that will be associated with the geometry
  35169. */
  35170. function Geometry(id, scene, vertexData, updatable, mesh) {
  35171. if (updatable === void 0) { updatable = false; }
  35172. if (mesh === void 0) { mesh = null; }
  35173. /**
  35174. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35175. */
  35176. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35177. this._totalVertices = 0;
  35178. this._isDisposed = false;
  35179. this._indexBufferIsUpdatable = false;
  35180. this.id = id;
  35181. this._engine = scene.getEngine();
  35182. this._meshes = [];
  35183. this._scene = scene;
  35184. //Init vertex buffer cache
  35185. this._vertexBuffers = {};
  35186. this._indices = [];
  35187. this._updatable = updatable;
  35188. // vertexData
  35189. if (vertexData) {
  35190. this.setAllVerticesData(vertexData, updatable);
  35191. }
  35192. else {
  35193. this._totalVertices = 0;
  35194. this._indices = [];
  35195. }
  35196. if (this._engine.getCaps().vertexArrayObject) {
  35197. this._vertexArrayObjects = {};
  35198. }
  35199. // applyToMesh
  35200. if (mesh) {
  35201. if (mesh.getClassName() === "LinesMesh") {
  35202. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35203. this.updateExtend();
  35204. }
  35205. this.applyToMesh(mesh);
  35206. mesh.computeWorldMatrix(true);
  35207. }
  35208. }
  35209. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35210. /**
  35211. * 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
  35212. */
  35213. get: function () {
  35214. return this._boundingBias;
  35215. },
  35216. /**
  35217. * 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
  35218. */
  35219. set: function (value) {
  35220. if (this._boundingBias && this._boundingBias.equals(value)) {
  35221. return;
  35222. }
  35223. this._boundingBias = value.clone();
  35224. this.updateBoundingInfo(true, null);
  35225. },
  35226. enumerable: true,
  35227. configurable: true
  35228. });
  35229. /**
  35230. * Static function used to attach a new empty geometry to a mesh
  35231. * @param mesh defines the mesh to attach the geometry to
  35232. * @returns the new {BABYLON.Geometry}
  35233. */
  35234. Geometry.CreateGeometryForMesh = function (mesh) {
  35235. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35236. geometry.applyToMesh(mesh);
  35237. return geometry;
  35238. };
  35239. Object.defineProperty(Geometry.prototype, "extend", {
  35240. /**
  35241. * Gets the current extend of the geometry
  35242. */
  35243. get: function () {
  35244. return this._extend;
  35245. },
  35246. enumerable: true,
  35247. configurable: true
  35248. });
  35249. /**
  35250. * Gets the hosting scene
  35251. * @returns the hosting {BABYLON.Scene}
  35252. */
  35253. Geometry.prototype.getScene = function () {
  35254. return this._scene;
  35255. };
  35256. /**
  35257. * Gets the hosting engine
  35258. * @returns the hosting {BABYLON.Engine}
  35259. */
  35260. Geometry.prototype.getEngine = function () {
  35261. return this._engine;
  35262. };
  35263. /**
  35264. * Defines if the geometry is ready to use
  35265. * @returns true if the geometry is ready to be used
  35266. */
  35267. Geometry.prototype.isReady = function () {
  35268. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35269. };
  35270. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35271. /**
  35272. * Gets a value indicating that the geometry should not be serialized
  35273. */
  35274. get: function () {
  35275. for (var index = 0; index < this._meshes.length; index++) {
  35276. if (!this._meshes[index].doNotSerialize) {
  35277. return false;
  35278. }
  35279. }
  35280. return true;
  35281. },
  35282. enumerable: true,
  35283. configurable: true
  35284. });
  35285. /** @ignore */
  35286. Geometry.prototype._rebuild = function () {
  35287. if (this._vertexArrayObjects) {
  35288. this._vertexArrayObjects = {};
  35289. }
  35290. // Index buffer
  35291. if (this._meshes.length !== 0 && this._indices) {
  35292. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35293. }
  35294. // Vertex buffers
  35295. for (var key in this._vertexBuffers) {
  35296. var vertexBuffer = this._vertexBuffers[key];
  35297. vertexBuffer._rebuild();
  35298. }
  35299. };
  35300. /**
  35301. * Affects all gemetry data in one call
  35302. * @param vertexData defines the geometry data
  35303. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35304. */
  35305. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35306. vertexData.applyToGeometry(this, updatable);
  35307. this.notifyUpdate();
  35308. };
  35309. /**
  35310. * Set specific vertex data
  35311. * @param kind defines the data kind (Position, normal, etc...)
  35312. * @param data defines the vertex data to use
  35313. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35314. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35315. */
  35316. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35317. if (updatable === void 0) { updatable = false; }
  35318. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35319. this.setVerticesBuffer(buffer);
  35320. };
  35321. /**
  35322. * Removes a specific vertex data
  35323. * @param kind defines the data kind (Position, normal, etc...)
  35324. */
  35325. Geometry.prototype.removeVerticesData = function (kind) {
  35326. if (this._vertexBuffers[kind]) {
  35327. this._vertexBuffers[kind].dispose();
  35328. delete this._vertexBuffers[kind];
  35329. }
  35330. };
  35331. /**
  35332. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35333. * @param buffer defines the vertex buffer to use
  35334. */
  35335. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35336. var kind = buffer.getKind();
  35337. if (this._vertexBuffers[kind]) {
  35338. this._vertexBuffers[kind].dispose();
  35339. }
  35340. this._vertexBuffers[kind] = buffer;
  35341. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35342. var data = buffer.getData();
  35343. var stride = buffer.getStrideSize();
  35344. this._totalVertices = data.length / stride;
  35345. this.updateExtend(data, stride);
  35346. this._resetPointsArrayCache();
  35347. var meshes = this._meshes;
  35348. var numOfMeshes = meshes.length;
  35349. for (var index = 0; index < numOfMeshes; index++) {
  35350. var mesh = meshes[index];
  35351. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35352. mesh._createGlobalSubMesh(false);
  35353. mesh.computeWorldMatrix(true);
  35354. }
  35355. }
  35356. this.notifyUpdate(kind);
  35357. if (this._vertexArrayObjects) {
  35358. this._disposeVertexArrayObjects();
  35359. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35360. }
  35361. };
  35362. /**
  35363. * Update a specific vertex buffer
  35364. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35365. * It will do nothing if the buffer is not updatable
  35366. * @param kind defines the data kind (Position, normal, etc...)
  35367. * @param data defines the data to use
  35368. * @param offset defines the offset in the target buffer where to store the data
  35369. */
  35370. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35371. var vertexBuffer = this.getVertexBuffer(kind);
  35372. if (!vertexBuffer) {
  35373. return;
  35374. }
  35375. vertexBuffer.updateDirectly(data, offset);
  35376. this.notifyUpdate(kind);
  35377. };
  35378. /**
  35379. * Update a specific vertex buffer
  35380. * This function will create a new buffer if the current one is not updatable
  35381. * @param kind defines the data kind (Position, normal, etc...)
  35382. * @param data defines the data to use
  35383. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35384. */
  35385. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35386. if (updateExtends === void 0) { updateExtends = false; }
  35387. var vertexBuffer = this.getVertexBuffer(kind);
  35388. if (!vertexBuffer) {
  35389. return;
  35390. }
  35391. vertexBuffer.update(data);
  35392. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35393. var stride = vertexBuffer.getStrideSize();
  35394. this._totalVertices = data.length / stride;
  35395. this.updateBoundingInfo(updateExtends, data);
  35396. }
  35397. this.notifyUpdate(kind);
  35398. };
  35399. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35400. if (updateExtends) {
  35401. this.updateExtend(data);
  35402. }
  35403. var meshes = this._meshes;
  35404. var numOfMeshes = meshes.length;
  35405. this._resetPointsArrayCache();
  35406. for (var index = 0; index < numOfMeshes; index++) {
  35407. var mesh = meshes[index];
  35408. if (updateExtends) {
  35409. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35410. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35411. var subMesh = mesh.subMeshes[subIndex];
  35412. subMesh.refreshBoundingInfo();
  35413. }
  35414. }
  35415. }
  35416. };
  35417. /** @ignore */
  35418. Geometry.prototype._bind = function (effect, indexToBind) {
  35419. if (!effect) {
  35420. return;
  35421. }
  35422. if (indexToBind === undefined) {
  35423. indexToBind = this._indexBuffer;
  35424. }
  35425. var vbs = this.getVertexBuffers();
  35426. if (!vbs) {
  35427. return;
  35428. }
  35429. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35430. this._engine.bindBuffers(vbs, indexToBind, effect);
  35431. return;
  35432. }
  35433. // Using VAO
  35434. if (!this._vertexArrayObjects[effect.key]) {
  35435. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35436. }
  35437. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35438. };
  35439. /**
  35440. * Gets total number of vertices
  35441. * @returns the total number of vertices
  35442. */
  35443. Geometry.prototype.getTotalVertices = function () {
  35444. if (!this.isReady()) {
  35445. return 0;
  35446. }
  35447. return this._totalVertices;
  35448. };
  35449. /**
  35450. * Gets a specific vertex data attached to this geometry
  35451. * @param kind defines the data kind (Position, normal, etc...)
  35452. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35453. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35454. * @returns a float array containing vertex data
  35455. */
  35456. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35457. var vertexBuffer = this.getVertexBuffer(kind);
  35458. if (!vertexBuffer) {
  35459. return null;
  35460. }
  35461. var orig = vertexBuffer.getData();
  35462. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35463. return orig;
  35464. }
  35465. else {
  35466. var len = orig.length;
  35467. var copy = [];
  35468. for (var i = 0; i < len; i++) {
  35469. copy.push(orig[i]);
  35470. }
  35471. return copy;
  35472. }
  35473. };
  35474. /**
  35475. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35476. * @param kind defines the data kind (Position, normal, etc...)
  35477. * @returns true if the vertex buffer with the specified kind is updatable
  35478. */
  35479. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35480. var vb = this._vertexBuffers[kind];
  35481. if (!vb) {
  35482. return false;
  35483. }
  35484. return vb.isUpdatable();
  35485. };
  35486. /**
  35487. * Gets a specific vertex buffer
  35488. * @param kind defines the data kind (Position, normal, etc...)
  35489. * @returns a {BABYLON.VertexBuffer}
  35490. */
  35491. Geometry.prototype.getVertexBuffer = function (kind) {
  35492. if (!this.isReady()) {
  35493. return null;
  35494. }
  35495. return this._vertexBuffers[kind];
  35496. };
  35497. /**
  35498. * Returns all vertex buffers
  35499. * @return an object holding all vertex buffers indexed by kind
  35500. */
  35501. Geometry.prototype.getVertexBuffers = function () {
  35502. if (!this.isReady()) {
  35503. return null;
  35504. }
  35505. return this._vertexBuffers;
  35506. };
  35507. /**
  35508. * Gets a boolean indicating if specific vertex buffer is present
  35509. * @param kind defines the data kind (Position, normal, etc...)
  35510. * @returns true if data is present
  35511. */
  35512. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35513. if (!this._vertexBuffers) {
  35514. if (this._delayInfo) {
  35515. return this._delayInfo.indexOf(kind) !== -1;
  35516. }
  35517. return false;
  35518. }
  35519. return this._vertexBuffers[kind] !== undefined;
  35520. };
  35521. /**
  35522. * Gets a list of all attached data kinds (Position, normal, etc...)
  35523. * @returns a list of string containing all kinds
  35524. */
  35525. Geometry.prototype.getVerticesDataKinds = function () {
  35526. var result = [];
  35527. var kind;
  35528. if (!this._vertexBuffers && this._delayInfo) {
  35529. for (kind in this._delayInfo) {
  35530. result.push(kind);
  35531. }
  35532. }
  35533. else {
  35534. for (kind in this._vertexBuffers) {
  35535. result.push(kind);
  35536. }
  35537. }
  35538. return result;
  35539. };
  35540. /**
  35541. * Update index buffer
  35542. * @param indices defines the indices to store in the index buffer
  35543. * @param offset defines the offset in the target buffer where to store the data
  35544. */
  35545. Geometry.prototype.updateIndices = function (indices, offset) {
  35546. if (!this._indexBuffer) {
  35547. return;
  35548. }
  35549. if (!this._indexBufferIsUpdatable) {
  35550. this.setIndices(indices, null, true);
  35551. }
  35552. else {
  35553. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35554. }
  35555. };
  35556. /**
  35557. * Creates a new index buffer
  35558. * @param indices defines the indices to store in the index buffer
  35559. * @param totalVertices defines the total number of vertices (could be null)
  35560. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35561. */
  35562. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35563. if (totalVertices === void 0) { totalVertices = null; }
  35564. if (updatable === void 0) { updatable = false; }
  35565. if (this._indexBuffer) {
  35566. this._engine._releaseBuffer(this._indexBuffer);
  35567. }
  35568. this._disposeVertexArrayObjects();
  35569. this._indices = indices;
  35570. this._indexBufferIsUpdatable = updatable;
  35571. if (this._meshes.length !== 0 && this._indices) {
  35572. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35573. }
  35574. if (totalVertices != undefined) {
  35575. this._totalVertices = totalVertices;
  35576. }
  35577. var meshes = this._meshes;
  35578. var numOfMeshes = meshes.length;
  35579. for (var index = 0; index < numOfMeshes; index++) {
  35580. meshes[index]._createGlobalSubMesh(true);
  35581. }
  35582. this.notifyUpdate();
  35583. };
  35584. /**
  35585. * Return the total number of indices
  35586. * @returns the total number of indices
  35587. */
  35588. Geometry.prototype.getTotalIndices = function () {
  35589. if (!this.isReady()) {
  35590. return 0;
  35591. }
  35592. return this._indices.length;
  35593. };
  35594. /**
  35595. * Gets the index buffer array
  35596. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35597. * @returns the index buffer array
  35598. */
  35599. Geometry.prototype.getIndices = function (copyWhenShared) {
  35600. if (!this.isReady()) {
  35601. return null;
  35602. }
  35603. var orig = this._indices;
  35604. if (!copyWhenShared || this._meshes.length === 1) {
  35605. return orig;
  35606. }
  35607. else {
  35608. var len = orig.length;
  35609. var copy = [];
  35610. for (var i = 0; i < len; i++) {
  35611. copy.push(orig[i]);
  35612. }
  35613. return copy;
  35614. }
  35615. };
  35616. /**
  35617. * Gets the index buffer
  35618. * @return the index buffer
  35619. */
  35620. Geometry.prototype.getIndexBuffer = function () {
  35621. if (!this.isReady()) {
  35622. return null;
  35623. }
  35624. return this._indexBuffer;
  35625. };
  35626. /** @ignore */
  35627. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35628. if (effect === void 0) { effect = null; }
  35629. if (!effect || !this._vertexArrayObjects) {
  35630. return;
  35631. }
  35632. if (this._vertexArrayObjects[effect.key]) {
  35633. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35634. delete this._vertexArrayObjects[effect.key];
  35635. }
  35636. };
  35637. /**
  35638. * Release the associated resources for a specific mesh
  35639. * @param mesh defines the source mesh
  35640. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35641. */
  35642. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35643. var meshes = this._meshes;
  35644. var index = meshes.indexOf(mesh);
  35645. if (index === -1) {
  35646. return;
  35647. }
  35648. meshes.splice(index, 1);
  35649. mesh._geometry = null;
  35650. if (meshes.length === 0 && shouldDispose) {
  35651. this.dispose();
  35652. }
  35653. };
  35654. /**
  35655. * Apply current geometry to a given mesh
  35656. * @param mesh defines the mesh to apply geometry to
  35657. */
  35658. Geometry.prototype.applyToMesh = function (mesh) {
  35659. if (mesh._geometry === this) {
  35660. return;
  35661. }
  35662. var previousGeometry = mesh._geometry;
  35663. if (previousGeometry) {
  35664. previousGeometry.releaseForMesh(mesh);
  35665. }
  35666. var meshes = this._meshes;
  35667. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35668. mesh._geometry = this;
  35669. this._scene.pushGeometry(this);
  35670. meshes.push(mesh);
  35671. if (this.isReady()) {
  35672. this._applyToMesh(mesh);
  35673. }
  35674. else {
  35675. mesh._boundingInfo = this._boundingInfo;
  35676. }
  35677. };
  35678. Geometry.prototype.updateExtend = function (data, stride) {
  35679. if (data === void 0) { data = null; }
  35680. if (!data) {
  35681. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35682. }
  35683. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35684. };
  35685. Geometry.prototype._applyToMesh = function (mesh) {
  35686. var numOfMeshes = this._meshes.length;
  35687. // vertexBuffers
  35688. for (var kind in this._vertexBuffers) {
  35689. if (numOfMeshes === 1) {
  35690. this._vertexBuffers[kind].create();
  35691. }
  35692. var buffer = this._vertexBuffers[kind].getBuffer();
  35693. if (buffer)
  35694. buffer.references = numOfMeshes;
  35695. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35696. if (!this._extend) {
  35697. this.updateExtend(this._vertexBuffers[kind].getData());
  35698. }
  35699. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35700. mesh._createGlobalSubMesh(false);
  35701. //bounding info was just created again, world matrix should be applied again.
  35702. mesh._updateBoundingInfo();
  35703. }
  35704. }
  35705. // indexBuffer
  35706. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35707. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35708. }
  35709. if (this._indexBuffer) {
  35710. this._indexBuffer.references = numOfMeshes;
  35711. }
  35712. };
  35713. Geometry.prototype.notifyUpdate = function (kind) {
  35714. if (this.onGeometryUpdated) {
  35715. this.onGeometryUpdated(this, kind);
  35716. }
  35717. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35718. var mesh = _a[_i];
  35719. mesh._markSubMeshesAsAttributesDirty();
  35720. }
  35721. };
  35722. /**
  35723. * Load the geometry if it was flagged as delay loaded
  35724. * @param scene defines the hosting scene
  35725. * @param onLoaded defines a callback called when the geometry is loaded
  35726. */
  35727. Geometry.prototype.load = function (scene, onLoaded) {
  35728. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35729. return;
  35730. }
  35731. if (this.isReady()) {
  35732. if (onLoaded) {
  35733. onLoaded();
  35734. }
  35735. return;
  35736. }
  35737. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35738. this._queueLoad(scene, onLoaded);
  35739. };
  35740. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35741. var _this = this;
  35742. if (!this.delayLoadingFile) {
  35743. return;
  35744. }
  35745. scene._addPendingData(this);
  35746. scene._loadFile(this.delayLoadingFile, function (data) {
  35747. if (!_this._delayLoadingFunction) {
  35748. return;
  35749. }
  35750. _this._delayLoadingFunction(JSON.parse(data), _this);
  35751. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35752. _this._delayInfo = [];
  35753. scene._removePendingData(_this);
  35754. var meshes = _this._meshes;
  35755. var numOfMeshes = meshes.length;
  35756. for (var index = 0; index < numOfMeshes; index++) {
  35757. _this._applyToMesh(meshes[index]);
  35758. }
  35759. if (onLoaded) {
  35760. onLoaded();
  35761. }
  35762. }, undefined, true);
  35763. };
  35764. /**
  35765. * Invert the geometry to move from a right handed system to a left handed one.
  35766. */
  35767. Geometry.prototype.toLeftHanded = function () {
  35768. // Flip faces
  35769. var tIndices = this.getIndices(false);
  35770. if (tIndices != null && tIndices.length > 0) {
  35771. for (var i = 0; i < tIndices.length; i += 3) {
  35772. var tTemp = tIndices[i + 0];
  35773. tIndices[i + 0] = tIndices[i + 2];
  35774. tIndices[i + 2] = tTemp;
  35775. }
  35776. this.setIndices(tIndices);
  35777. }
  35778. // Negate position.z
  35779. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35780. if (tPositions != null && tPositions.length > 0) {
  35781. for (var i = 0; i < tPositions.length; i += 3) {
  35782. tPositions[i + 2] = -tPositions[i + 2];
  35783. }
  35784. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35785. }
  35786. // Negate normal.z
  35787. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35788. if (tNormals != null && tNormals.length > 0) {
  35789. for (var i = 0; i < tNormals.length; i += 3) {
  35790. tNormals[i + 2] = -tNormals[i + 2];
  35791. }
  35792. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35793. }
  35794. };
  35795. // Cache
  35796. /** @ignore */
  35797. Geometry.prototype._resetPointsArrayCache = function () {
  35798. this._positions = null;
  35799. };
  35800. /** @ignore */
  35801. Geometry.prototype._generatePointsArray = function () {
  35802. if (this._positions)
  35803. return true;
  35804. this._positions = [];
  35805. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35806. if (!data) {
  35807. return false;
  35808. }
  35809. for (var index = 0; index < data.length; index += 3) {
  35810. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35811. }
  35812. return true;
  35813. };
  35814. /**
  35815. * Gets a value indicating if the geometry is disposed
  35816. * @returns true if the geometry was disposed
  35817. */
  35818. Geometry.prototype.isDisposed = function () {
  35819. return this._isDisposed;
  35820. };
  35821. Geometry.prototype._disposeVertexArrayObjects = function () {
  35822. if (this._vertexArrayObjects) {
  35823. for (var kind in this._vertexArrayObjects) {
  35824. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35825. }
  35826. this._vertexArrayObjects = {};
  35827. }
  35828. };
  35829. /**
  35830. * Free all associated resources
  35831. */
  35832. Geometry.prototype.dispose = function () {
  35833. var meshes = this._meshes;
  35834. var numOfMeshes = meshes.length;
  35835. var index;
  35836. for (index = 0; index < numOfMeshes; index++) {
  35837. this.releaseForMesh(meshes[index]);
  35838. }
  35839. this._meshes = [];
  35840. this._disposeVertexArrayObjects();
  35841. for (var kind in this._vertexBuffers) {
  35842. this._vertexBuffers[kind].dispose();
  35843. }
  35844. this._vertexBuffers = {};
  35845. this._totalVertices = 0;
  35846. if (this._indexBuffer) {
  35847. this._engine._releaseBuffer(this._indexBuffer);
  35848. }
  35849. this._indexBuffer = null;
  35850. this._indices = [];
  35851. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35852. this.delayLoadingFile = null;
  35853. this._delayLoadingFunction = null;
  35854. this._delayInfo = [];
  35855. this._boundingInfo = null;
  35856. this._scene.removeGeometry(this);
  35857. this._isDisposed = true;
  35858. };
  35859. /**
  35860. * Clone the current geometry into a new geometry
  35861. * @param id defines the unique ID of the new geometry
  35862. * @returns a new geometry object
  35863. */
  35864. Geometry.prototype.copy = function (id) {
  35865. var vertexData = new BABYLON.VertexData();
  35866. vertexData.indices = [];
  35867. var indices = this.getIndices();
  35868. if (indices) {
  35869. for (var index = 0; index < indices.length; index++) {
  35870. vertexData.indices.push(indices[index]);
  35871. }
  35872. }
  35873. var updatable = false;
  35874. var stopChecking = false;
  35875. var kind;
  35876. for (kind in this._vertexBuffers) {
  35877. // using slice() to make a copy of the array and not just reference it
  35878. var data = this.getVerticesData(kind);
  35879. if (data instanceof Float32Array) {
  35880. vertexData.set(new Float32Array(data), kind);
  35881. }
  35882. else {
  35883. vertexData.set(data.slice(0), kind);
  35884. }
  35885. if (!stopChecking) {
  35886. var vb = this.getVertexBuffer(kind);
  35887. if (vb) {
  35888. updatable = vb.isUpdatable();
  35889. stopChecking = !updatable;
  35890. }
  35891. }
  35892. }
  35893. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35894. geometry.delayLoadState = this.delayLoadState;
  35895. geometry.delayLoadingFile = this.delayLoadingFile;
  35896. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35897. for (kind in this._delayInfo) {
  35898. geometry._delayInfo = geometry._delayInfo || [];
  35899. geometry._delayInfo.push(kind);
  35900. }
  35901. // Bounding info
  35902. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35903. return geometry;
  35904. };
  35905. /**
  35906. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35907. * @return a JSON representation of the current geometry data (without the vertices data)
  35908. */
  35909. Geometry.prototype.serialize = function () {
  35910. var serializationObject = {};
  35911. serializationObject.id = this.id;
  35912. serializationObject.updatable = this._updatable;
  35913. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35914. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35915. }
  35916. return serializationObject;
  35917. };
  35918. Geometry.prototype.toNumberArray = function (origin) {
  35919. if (Array.isArray(origin)) {
  35920. return origin;
  35921. }
  35922. else {
  35923. return Array.prototype.slice.call(origin);
  35924. }
  35925. };
  35926. /**
  35927. * Serialize all vertices data into a JSON oject
  35928. * @returns a JSON representation of the current geometry data
  35929. */
  35930. Geometry.prototype.serializeVerticeData = function () {
  35931. var serializationObject = this.serialize();
  35932. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35933. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35934. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35935. serializationObject.positions._updatable = true;
  35936. }
  35937. }
  35938. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35939. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35940. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35941. serializationObject.normals._updatable = true;
  35942. }
  35943. }
  35944. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35945. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35946. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35947. serializationObject.tangets._updatable = true;
  35948. }
  35949. }
  35950. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35951. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35952. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35953. serializationObject.uvs._updatable = true;
  35954. }
  35955. }
  35956. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35957. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35958. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35959. serializationObject.uv2s._updatable = true;
  35960. }
  35961. }
  35962. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35963. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35964. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35965. serializationObject.uv3s._updatable = true;
  35966. }
  35967. }
  35968. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35969. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35970. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35971. serializationObject.uv4s._updatable = true;
  35972. }
  35973. }
  35974. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35975. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35976. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35977. serializationObject.uv5s._updatable = true;
  35978. }
  35979. }
  35980. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35981. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35982. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35983. serializationObject.uv6s._updatable = true;
  35984. }
  35985. }
  35986. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35987. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35988. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35989. serializationObject.colors._updatable = true;
  35990. }
  35991. }
  35992. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35993. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35994. serializationObject.matricesIndices._isExpanded = true;
  35995. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35996. serializationObject.matricesIndices._updatable = true;
  35997. }
  35998. }
  35999. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36000. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36001. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36002. serializationObject.matricesWeights._updatable = true;
  36003. }
  36004. }
  36005. serializationObject.indices = this.toNumberArray(this.getIndices());
  36006. return serializationObject;
  36007. };
  36008. // Statics
  36009. /**
  36010. * Extracts a clone of a mesh geometry
  36011. * @param mesh defines the source mesh
  36012. * @param id defines the unique ID of the new geometry object
  36013. * @returns the new geometry object
  36014. */
  36015. Geometry.ExtractFromMesh = function (mesh, id) {
  36016. var geometry = mesh._geometry;
  36017. if (!geometry) {
  36018. return null;
  36019. }
  36020. return geometry.copy(id);
  36021. };
  36022. /**
  36023. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36024. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36025. * Be aware Math.random() could cause collisions, but:
  36026. * "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"
  36027. * @returns a string containing a new GUID
  36028. */
  36029. Geometry.RandomId = function () {
  36030. return BABYLON.Tools.RandomId();
  36031. };
  36032. /** @ignore */
  36033. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36034. var scene = mesh.getScene();
  36035. // Geometry
  36036. var geometryId = parsedGeometry.geometryId;
  36037. if (geometryId) {
  36038. var geometry = scene.getGeometryByID(geometryId);
  36039. if (geometry) {
  36040. geometry.applyToMesh(mesh);
  36041. }
  36042. }
  36043. else if (parsedGeometry instanceof ArrayBuffer) {
  36044. var binaryInfo = mesh._binaryInfo;
  36045. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36046. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36047. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36048. }
  36049. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36050. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36051. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36052. }
  36053. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36054. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36055. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36056. }
  36057. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36058. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36059. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36060. }
  36061. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36062. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36063. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36064. }
  36065. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36066. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36067. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36068. }
  36069. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36070. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36071. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36072. }
  36073. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36074. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36075. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36076. }
  36077. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36078. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36079. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36080. }
  36081. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36082. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36083. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36084. }
  36085. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36086. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36087. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36088. }
  36089. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36090. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36091. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36092. }
  36093. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36094. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36095. mesh.setIndices(indicesData, null);
  36096. }
  36097. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36098. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36099. mesh.subMeshes = [];
  36100. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36101. var materialIndex = subMeshesData[(i * 5) + 0];
  36102. var verticesStart = subMeshesData[(i * 5) + 1];
  36103. var verticesCount = subMeshesData[(i * 5) + 2];
  36104. var indexStart = subMeshesData[(i * 5) + 3];
  36105. var indexCount = subMeshesData[(i * 5) + 4];
  36106. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36107. }
  36108. }
  36109. }
  36110. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36111. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36112. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36113. if (parsedGeometry.tangents) {
  36114. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36115. }
  36116. if (parsedGeometry.uvs) {
  36117. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36118. }
  36119. if (parsedGeometry.uvs2) {
  36120. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36121. }
  36122. if (parsedGeometry.uvs3) {
  36123. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36124. }
  36125. if (parsedGeometry.uvs4) {
  36126. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36127. }
  36128. if (parsedGeometry.uvs5) {
  36129. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36130. }
  36131. if (parsedGeometry.uvs6) {
  36132. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36133. }
  36134. if (parsedGeometry.colors) {
  36135. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36136. }
  36137. if (parsedGeometry.matricesIndices) {
  36138. if (!parsedGeometry.matricesIndices._isExpanded) {
  36139. var floatIndices = [];
  36140. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36141. var matricesIndex = parsedGeometry.matricesIndices[i];
  36142. floatIndices.push(matricesIndex & 0x000000FF);
  36143. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36144. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36145. floatIndices.push(matricesIndex >> 24);
  36146. }
  36147. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36148. }
  36149. else {
  36150. delete parsedGeometry.matricesIndices._isExpanded;
  36151. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36152. }
  36153. }
  36154. if (parsedGeometry.matricesIndicesExtra) {
  36155. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36156. var floatIndices = [];
  36157. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36158. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36159. floatIndices.push(matricesIndex & 0x000000FF);
  36160. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36161. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36162. floatIndices.push(matricesIndex >> 24);
  36163. }
  36164. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36165. }
  36166. else {
  36167. delete parsedGeometry.matricesIndices._isExpanded;
  36168. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36169. }
  36170. }
  36171. if (parsedGeometry.matricesWeights) {
  36172. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36173. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36174. }
  36175. if (parsedGeometry.matricesWeightsExtra) {
  36176. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36177. }
  36178. mesh.setIndices(parsedGeometry.indices, null);
  36179. }
  36180. // SubMeshes
  36181. if (parsedGeometry.subMeshes) {
  36182. mesh.subMeshes = [];
  36183. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36184. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36185. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36186. }
  36187. }
  36188. // Flat shading
  36189. if (mesh._shouldGenerateFlatShading) {
  36190. mesh.convertToFlatShadedMesh();
  36191. delete mesh._shouldGenerateFlatShading;
  36192. }
  36193. // Update
  36194. mesh.computeWorldMatrix(true);
  36195. // Octree
  36196. var sceneOctree = scene.selectionOctree;
  36197. if (sceneOctree !== undefined && sceneOctree !== null) {
  36198. sceneOctree.addMesh(mesh);
  36199. }
  36200. };
  36201. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36202. var epsilon = 1e-3;
  36203. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36204. return;
  36205. }
  36206. var noInfluenceBoneIndex = 0.0;
  36207. if (parsedGeometry.skeletonId > -1) {
  36208. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36209. if (!skeleton) {
  36210. return;
  36211. }
  36212. noInfluenceBoneIndex = skeleton.bones.length;
  36213. }
  36214. else {
  36215. return;
  36216. }
  36217. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36218. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36219. var matricesWeights = parsedGeometry.matricesWeights;
  36220. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36221. var influencers = parsedGeometry.numBoneInfluencer;
  36222. var size = matricesWeights.length;
  36223. for (var i = 0; i < size; i += 4) {
  36224. var weight = 0.0;
  36225. var firstZeroWeight = -1;
  36226. for (var j = 0; j < 4; j++) {
  36227. var w = matricesWeights[i + j];
  36228. weight += w;
  36229. if (w < epsilon && firstZeroWeight < 0) {
  36230. firstZeroWeight = j;
  36231. }
  36232. }
  36233. if (matricesWeightsExtra) {
  36234. for (var j = 0; j < 4; j++) {
  36235. var w = matricesWeightsExtra[i + j];
  36236. weight += w;
  36237. if (w < epsilon && firstZeroWeight < 0) {
  36238. firstZeroWeight = j + 4;
  36239. }
  36240. }
  36241. }
  36242. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36243. firstZeroWeight = influencers - 1;
  36244. }
  36245. if (weight > epsilon) {
  36246. var mweight = 1.0 / weight;
  36247. for (var j = 0; j < 4; j++) {
  36248. matricesWeights[i + j] *= mweight;
  36249. }
  36250. if (matricesWeightsExtra) {
  36251. for (var j = 0; j < 4; j++) {
  36252. matricesWeightsExtra[i + j] *= mweight;
  36253. }
  36254. }
  36255. }
  36256. else {
  36257. if (firstZeroWeight >= 4) {
  36258. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36259. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36260. }
  36261. else {
  36262. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36263. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36264. }
  36265. }
  36266. }
  36267. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36268. if (parsedGeometry.matricesWeightsExtra) {
  36269. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36270. }
  36271. };
  36272. /**
  36273. * Create a new geometry from persisted data (Using .babylon file format)
  36274. * @param parsedVertexData defines the persisted data
  36275. * @param scene defines the hosting scene
  36276. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36277. * @returns the new geometry object
  36278. */
  36279. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36280. if (scene.getGeometryByID(parsedVertexData.id)) {
  36281. return null; // null since geometry could be something else than a box...
  36282. }
  36283. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36284. if (BABYLON.Tags) {
  36285. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36286. }
  36287. if (parsedVertexData.delayLoadingFile) {
  36288. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36289. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36290. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36291. geometry._delayInfo = [];
  36292. if (parsedVertexData.hasUVs) {
  36293. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36294. }
  36295. if (parsedVertexData.hasUVs2) {
  36296. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36297. }
  36298. if (parsedVertexData.hasUVs3) {
  36299. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36300. }
  36301. if (parsedVertexData.hasUVs4) {
  36302. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36303. }
  36304. if (parsedVertexData.hasUVs5) {
  36305. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36306. }
  36307. if (parsedVertexData.hasUVs6) {
  36308. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36309. }
  36310. if (parsedVertexData.hasColors) {
  36311. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36312. }
  36313. if (parsedVertexData.hasMatricesIndices) {
  36314. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36315. }
  36316. if (parsedVertexData.hasMatricesWeights) {
  36317. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36318. }
  36319. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36320. }
  36321. else {
  36322. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36323. }
  36324. scene.pushGeometry(geometry, true);
  36325. return geometry;
  36326. };
  36327. return Geometry;
  36328. }());
  36329. BABYLON.Geometry = Geometry;
  36330. // Primitives
  36331. /// Abstract class
  36332. /**
  36333. * Abstract class used to provide common services for all typed geometries
  36334. */
  36335. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36336. __extends(_PrimitiveGeometry, _super);
  36337. /**
  36338. * Creates a new typed geometry
  36339. * @param id defines the unique ID of the geometry
  36340. * @param scene defines the hosting scene
  36341. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36342. * @param mesh defines the hosting mesh (can be null)
  36343. */
  36344. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36345. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36346. if (mesh === void 0) { mesh = null; }
  36347. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36348. _this._canBeRegenerated = _canBeRegenerated;
  36349. _this._beingRegenerated = true;
  36350. _this.regenerate();
  36351. _this._beingRegenerated = false;
  36352. return _this;
  36353. }
  36354. /**
  36355. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36356. * @returns true if the geometry can be regenerated
  36357. */
  36358. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36359. return this._canBeRegenerated;
  36360. };
  36361. /**
  36362. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36363. */
  36364. _PrimitiveGeometry.prototype.regenerate = function () {
  36365. if (!this._canBeRegenerated) {
  36366. return;
  36367. }
  36368. this._beingRegenerated = true;
  36369. this.setAllVerticesData(this._regenerateVertexData(), false);
  36370. this._beingRegenerated = false;
  36371. };
  36372. /**
  36373. * Clone the geometry
  36374. * @param id defines the unique ID of the new geometry
  36375. * @returns the new geometry
  36376. */
  36377. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36378. return _super.prototype.copy.call(this, id);
  36379. };
  36380. // overrides
  36381. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36382. if (!this._beingRegenerated) {
  36383. return;
  36384. }
  36385. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36386. };
  36387. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36388. if (!this._beingRegenerated) {
  36389. return;
  36390. }
  36391. _super.prototype.setVerticesData.call(this, kind, data, false);
  36392. };
  36393. // to override
  36394. /** @ignore */
  36395. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36396. throw new Error("Abstract method");
  36397. };
  36398. _PrimitiveGeometry.prototype.copy = function (id) {
  36399. throw new Error("Must be overriden in sub-classes.");
  36400. };
  36401. _PrimitiveGeometry.prototype.serialize = function () {
  36402. var serializationObject = _super.prototype.serialize.call(this);
  36403. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36404. return serializationObject;
  36405. };
  36406. return _PrimitiveGeometry;
  36407. }(Geometry));
  36408. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36409. /**
  36410. * Creates a ribbon geometry
  36411. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36412. */
  36413. var RibbonGeometry = /** @class */ (function (_super) {
  36414. __extends(RibbonGeometry, _super);
  36415. /**
  36416. * Creates a ribbon geometry
  36417. * @param id defines the unique ID of the geometry
  36418. * @param scene defines the hosting scene
  36419. * @param pathArray defines the array of paths to use
  36420. * @param closeArray defines if the last path and the first path must be joined
  36421. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36422. * @param offset defines the offset between points
  36423. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36424. * @param mesh defines the hosting mesh (can be null)
  36425. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36426. */
  36427. function RibbonGeometry(id, scene,
  36428. /**
  36429. * Defines the array of paths to use
  36430. */
  36431. pathArray,
  36432. /**
  36433. * Defines if the last and first points of each path in your pathArray must be joined
  36434. */
  36435. closeArray,
  36436. /**
  36437. * Defines if the last and first points of each path in your pathArray must be joined
  36438. */
  36439. closePath,
  36440. /**
  36441. * Defines the offset between points
  36442. */
  36443. offset, canBeRegenerated, mesh,
  36444. /**
  36445. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36446. */
  36447. side) {
  36448. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36449. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36450. _this.pathArray = pathArray;
  36451. _this.closeArray = closeArray;
  36452. _this.closePath = closePath;
  36453. _this.offset = offset;
  36454. _this.side = side;
  36455. return _this;
  36456. }
  36457. /** @ignore */
  36458. RibbonGeometry.prototype._regenerateVertexData = function () {
  36459. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36460. };
  36461. RibbonGeometry.prototype.copy = function (id) {
  36462. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36463. };
  36464. return RibbonGeometry;
  36465. }(_PrimitiveGeometry));
  36466. BABYLON.RibbonGeometry = RibbonGeometry;
  36467. /**
  36468. * Creates a box geometry
  36469. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36470. */
  36471. var BoxGeometry = /** @class */ (function (_super) {
  36472. __extends(BoxGeometry, _super);
  36473. /**
  36474. * Creates a box geometry
  36475. * @param id defines the unique ID of the geometry
  36476. * @param scene defines the hosting scene
  36477. * @param size defines the zise of the box (width, height and depth are the same)
  36478. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36479. * @param mesh defines the hosting mesh (can be null)
  36480. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36481. */
  36482. function BoxGeometry(id, scene,
  36483. /**
  36484. * Defines the zise of the box (width, height and depth are the same)
  36485. */
  36486. size, canBeRegenerated, mesh,
  36487. /**
  36488. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36489. */
  36490. side) {
  36491. if (mesh === void 0) { mesh = null; }
  36492. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36493. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36494. _this.size = size;
  36495. _this.side = side;
  36496. return _this;
  36497. }
  36498. BoxGeometry.prototype._regenerateVertexData = function () {
  36499. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36500. };
  36501. BoxGeometry.prototype.copy = function (id) {
  36502. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36503. };
  36504. BoxGeometry.prototype.serialize = function () {
  36505. var serializationObject = _super.prototype.serialize.call(this);
  36506. serializationObject.size = this.size;
  36507. return serializationObject;
  36508. };
  36509. BoxGeometry.Parse = function (parsedBox, scene) {
  36510. if (scene.getGeometryByID(parsedBox.id)) {
  36511. return null; // null since geometry could be something else than a box...
  36512. }
  36513. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36514. if (BABYLON.Tags) {
  36515. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36516. }
  36517. scene.pushGeometry(box, true);
  36518. return box;
  36519. };
  36520. return BoxGeometry;
  36521. }(_PrimitiveGeometry));
  36522. BABYLON.BoxGeometry = BoxGeometry;
  36523. /**
  36524. * Creates a sphere geometry
  36525. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36526. */
  36527. var SphereGeometry = /** @class */ (function (_super) {
  36528. __extends(SphereGeometry, _super);
  36529. /**
  36530. * Create a new sphere geometry
  36531. * @param id defines the unique ID of the geometry
  36532. * @param scene defines the hosting scene
  36533. * @param segments defines the number of segments to use to create the sphere
  36534. * @param diameter defines the diameter of the sphere
  36535. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36536. * @param mesh defines the hosting mesh (can be null)
  36537. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36538. */
  36539. function SphereGeometry(id, scene,
  36540. /**
  36541. * Defines the number of segments to use to create the sphere
  36542. */
  36543. segments,
  36544. /**
  36545. * Defines the diameter of the sphere
  36546. */
  36547. diameter, canBeRegenerated, mesh,
  36548. /**
  36549. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36550. */
  36551. side) {
  36552. if (mesh === void 0) { mesh = null; }
  36553. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36554. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36555. _this.segments = segments;
  36556. _this.diameter = diameter;
  36557. _this.side = side;
  36558. return _this;
  36559. }
  36560. SphereGeometry.prototype._regenerateVertexData = function () {
  36561. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36562. };
  36563. SphereGeometry.prototype.copy = function (id) {
  36564. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36565. };
  36566. SphereGeometry.prototype.serialize = function () {
  36567. var serializationObject = _super.prototype.serialize.call(this);
  36568. serializationObject.segments = this.segments;
  36569. serializationObject.diameter = this.diameter;
  36570. return serializationObject;
  36571. };
  36572. SphereGeometry.Parse = function (parsedSphere, scene) {
  36573. if (scene.getGeometryByID(parsedSphere.id)) {
  36574. return null; // null since geometry could be something else than a sphere...
  36575. }
  36576. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36577. if (BABYLON.Tags) {
  36578. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36579. }
  36580. scene.pushGeometry(sphere, true);
  36581. return sphere;
  36582. };
  36583. return SphereGeometry;
  36584. }(_PrimitiveGeometry));
  36585. BABYLON.SphereGeometry = SphereGeometry;
  36586. /**
  36587. * Creates a disc geometry
  36588. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36589. */
  36590. var DiscGeometry = /** @class */ (function (_super) {
  36591. __extends(DiscGeometry, _super);
  36592. /**
  36593. * Creates a new disc geometry
  36594. * @param id defines the unique ID of the geometry
  36595. * @param scene defines the hosting scene
  36596. * @param radius defines the radius of the disc
  36597. * @param tessellation defines the tesselation factor to apply to the disc
  36598. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36599. * @param mesh defines the hosting mesh (can be null)
  36600. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36601. */
  36602. function DiscGeometry(id, scene,
  36603. /**
  36604. * Defines the radius of the disc
  36605. */
  36606. radius,
  36607. /**
  36608. * Defines the tesselation factor to apply to the disc
  36609. */
  36610. tessellation, canBeRegenerated, mesh,
  36611. /**
  36612. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36613. */
  36614. side) {
  36615. if (mesh === void 0) { mesh = null; }
  36616. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36617. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36618. _this.radius = radius;
  36619. _this.tessellation = tessellation;
  36620. _this.side = side;
  36621. return _this;
  36622. }
  36623. DiscGeometry.prototype._regenerateVertexData = function () {
  36624. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36625. };
  36626. DiscGeometry.prototype.copy = function (id) {
  36627. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36628. };
  36629. return DiscGeometry;
  36630. }(_PrimitiveGeometry));
  36631. BABYLON.DiscGeometry = DiscGeometry;
  36632. /**
  36633. * Creates a new cylinder geometry
  36634. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36635. */
  36636. var CylinderGeometry = /** @class */ (function (_super) {
  36637. __extends(CylinderGeometry, _super);
  36638. /**
  36639. * Creates a new cylinder geometry
  36640. * @param id defines the unique ID of the geometry
  36641. * @param scene defines the hosting scene
  36642. * @param height defines the height of the cylinder
  36643. * @param diameterTop defines the diameter of the cylinder's top cap
  36644. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36645. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36646. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36647. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36648. * @param mesh defines the hosting mesh (can be null)
  36649. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36650. */
  36651. function CylinderGeometry(id, scene,
  36652. /**
  36653. * Defines the height of the cylinder
  36654. */
  36655. height,
  36656. /**
  36657. * Defines the diameter of the cylinder's top cap
  36658. */
  36659. diameterTop,
  36660. /**
  36661. * Defines the diameter of the cylinder's bottom cap
  36662. */
  36663. diameterBottom,
  36664. /**
  36665. * Defines the tessellation factor to apply to the cylinder
  36666. */
  36667. tessellation,
  36668. /**
  36669. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36670. */
  36671. subdivisions, canBeRegenerated, mesh,
  36672. /**
  36673. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36674. */
  36675. side) {
  36676. if (subdivisions === void 0) { subdivisions = 1; }
  36677. if (mesh === void 0) { mesh = null; }
  36678. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36679. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36680. _this.height = height;
  36681. _this.diameterTop = diameterTop;
  36682. _this.diameterBottom = diameterBottom;
  36683. _this.tessellation = tessellation;
  36684. _this.subdivisions = subdivisions;
  36685. _this.side = side;
  36686. return _this;
  36687. }
  36688. CylinderGeometry.prototype._regenerateVertexData = function () {
  36689. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36690. };
  36691. CylinderGeometry.prototype.copy = function (id) {
  36692. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36693. };
  36694. CylinderGeometry.prototype.serialize = function () {
  36695. var serializationObject = _super.prototype.serialize.call(this);
  36696. serializationObject.height = this.height;
  36697. serializationObject.diameterTop = this.diameterTop;
  36698. serializationObject.diameterBottom = this.diameterBottom;
  36699. serializationObject.tessellation = this.tessellation;
  36700. return serializationObject;
  36701. };
  36702. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36703. if (scene.getGeometryByID(parsedCylinder.id)) {
  36704. return null; // null since geometry could be something else than a cylinder...
  36705. }
  36706. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36707. if (BABYLON.Tags) {
  36708. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36709. }
  36710. scene.pushGeometry(cylinder, true);
  36711. return cylinder;
  36712. };
  36713. return CylinderGeometry;
  36714. }(_PrimitiveGeometry));
  36715. BABYLON.CylinderGeometry = CylinderGeometry;
  36716. /**
  36717. * Creates a new torus geometry
  36718. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36719. */
  36720. var TorusGeometry = /** @class */ (function (_super) {
  36721. __extends(TorusGeometry, _super);
  36722. /**
  36723. * Creates a new torus geometry
  36724. * @param id defines the unique ID of the geometry
  36725. * @param scene defines the hosting scene
  36726. * @param diameter defines the diameter of the torus
  36727. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36728. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36729. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36730. * @param mesh defines the hosting mesh (can be null)
  36731. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36732. */
  36733. function TorusGeometry(id, scene,
  36734. /**
  36735. * Defines the diameter of the torus
  36736. */
  36737. diameter,
  36738. /**
  36739. * Defines the thickness of the torus (ie. internal diameter)
  36740. */
  36741. thickness,
  36742. /**
  36743. * Defines the tesselation factor to apply to the torus
  36744. */
  36745. tessellation, canBeRegenerated, mesh,
  36746. /**
  36747. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36748. */
  36749. side) {
  36750. if (mesh === void 0) { mesh = null; }
  36751. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36752. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36753. _this.diameter = diameter;
  36754. _this.thickness = thickness;
  36755. _this.tessellation = tessellation;
  36756. _this.side = side;
  36757. return _this;
  36758. }
  36759. TorusGeometry.prototype._regenerateVertexData = function () {
  36760. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36761. };
  36762. TorusGeometry.prototype.copy = function (id) {
  36763. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36764. };
  36765. TorusGeometry.prototype.serialize = function () {
  36766. var serializationObject = _super.prototype.serialize.call(this);
  36767. serializationObject.diameter = this.diameter;
  36768. serializationObject.thickness = this.thickness;
  36769. serializationObject.tessellation = this.tessellation;
  36770. return serializationObject;
  36771. };
  36772. TorusGeometry.Parse = function (parsedTorus, scene) {
  36773. if (scene.getGeometryByID(parsedTorus.id)) {
  36774. return null; // null since geometry could be something else than a torus...
  36775. }
  36776. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36777. if (BABYLON.Tags) {
  36778. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36779. }
  36780. scene.pushGeometry(torus, true);
  36781. return torus;
  36782. };
  36783. return TorusGeometry;
  36784. }(_PrimitiveGeometry));
  36785. BABYLON.TorusGeometry = TorusGeometry;
  36786. /**
  36787. * Creates a new ground geometry
  36788. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36789. */
  36790. var GroundGeometry = /** @class */ (function (_super) {
  36791. __extends(GroundGeometry, _super);
  36792. /**
  36793. * Creates a new ground geometry
  36794. * @param id defines the unique ID of the geometry
  36795. * @param scene defines the hosting scene
  36796. * @param width defines the width of the ground
  36797. * @param height defines the height of the ground
  36798. * @param subdivisions defines the subdivisions to apply to the ground
  36799. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36800. * @param mesh defines the hosting mesh (can be null)
  36801. */
  36802. function GroundGeometry(id, scene,
  36803. /**
  36804. * Defines the width of the ground
  36805. */
  36806. width,
  36807. /**
  36808. * Defines the height of the ground
  36809. */
  36810. height,
  36811. /**
  36812. * Defines the subdivisions to apply to the ground
  36813. */
  36814. subdivisions, canBeRegenerated, mesh) {
  36815. if (mesh === void 0) { mesh = null; }
  36816. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36817. _this.width = width;
  36818. _this.height = height;
  36819. _this.subdivisions = subdivisions;
  36820. return _this;
  36821. }
  36822. GroundGeometry.prototype._regenerateVertexData = function () {
  36823. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36824. };
  36825. GroundGeometry.prototype.copy = function (id) {
  36826. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36827. };
  36828. GroundGeometry.prototype.serialize = function () {
  36829. var serializationObject = _super.prototype.serialize.call(this);
  36830. serializationObject.width = this.width;
  36831. serializationObject.height = this.height;
  36832. serializationObject.subdivisions = this.subdivisions;
  36833. return serializationObject;
  36834. };
  36835. GroundGeometry.Parse = function (parsedGround, scene) {
  36836. if (scene.getGeometryByID(parsedGround.id)) {
  36837. return null; // null since geometry could be something else than a ground...
  36838. }
  36839. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36840. if (BABYLON.Tags) {
  36841. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36842. }
  36843. scene.pushGeometry(ground, true);
  36844. return ground;
  36845. };
  36846. return GroundGeometry;
  36847. }(_PrimitiveGeometry));
  36848. BABYLON.GroundGeometry = GroundGeometry;
  36849. /**
  36850. * Creates a tiled ground geometry
  36851. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36852. */
  36853. var TiledGroundGeometry = /** @class */ (function (_super) {
  36854. __extends(TiledGroundGeometry, _super);
  36855. /**
  36856. * Creates a tiled ground geometry
  36857. * @param id defines the unique ID of the geometry
  36858. * @param scene defines the hosting scene
  36859. * @param xmin defines the minimum value on X axis
  36860. * @param zmin defines the minimum value on Z axis
  36861. * @param xmax defines the maximum value on X axis
  36862. * @param zmax defines the maximum value on Z axis
  36863. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36864. * @param precision defines the precision to use when computing the tiles
  36865. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36866. * @param mesh defines the hosting mesh (can be null)
  36867. */
  36868. function TiledGroundGeometry(id, scene,
  36869. /**
  36870. * Defines the minimum value on X axis
  36871. */
  36872. xmin,
  36873. /**
  36874. * Defines the minimum value on Z axis
  36875. */
  36876. zmin,
  36877. /**
  36878. * Defines the maximum value on X axis
  36879. */
  36880. xmax,
  36881. /**
  36882. * Defines the maximum value on Z axis
  36883. */
  36884. zmax,
  36885. /**
  36886. * Defines the subdivisions to apply to the ground
  36887. */
  36888. subdivisions,
  36889. /**
  36890. * Defines the precision to use when computing the tiles
  36891. */
  36892. precision, canBeRegenerated, mesh) {
  36893. if (mesh === void 0) { mesh = null; }
  36894. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36895. _this.xmin = xmin;
  36896. _this.zmin = zmin;
  36897. _this.xmax = xmax;
  36898. _this.zmax = zmax;
  36899. _this.subdivisions = subdivisions;
  36900. _this.precision = precision;
  36901. return _this;
  36902. }
  36903. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36904. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36905. };
  36906. TiledGroundGeometry.prototype.copy = function (id) {
  36907. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36908. };
  36909. return TiledGroundGeometry;
  36910. }(_PrimitiveGeometry));
  36911. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36912. /**
  36913. * Creates a plane geometry
  36914. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36915. */
  36916. var PlaneGeometry = /** @class */ (function (_super) {
  36917. __extends(PlaneGeometry, _super);
  36918. /**
  36919. * Creates a plane geometry
  36920. * @param id defines the unique ID of the geometry
  36921. * @param scene defines the hosting scene
  36922. * @param size defines the size of the plane (width === height)
  36923. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36924. * @param mesh defines the hosting mesh (can be null)
  36925. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36926. */
  36927. function PlaneGeometry(id, scene,
  36928. /**
  36929. * Defines the size of the plane (width === height)
  36930. */
  36931. size, canBeRegenerated, mesh,
  36932. /**
  36933. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36934. */
  36935. side) {
  36936. if (mesh === void 0) { mesh = null; }
  36937. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36938. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36939. _this.size = size;
  36940. _this.side = side;
  36941. return _this;
  36942. }
  36943. PlaneGeometry.prototype._regenerateVertexData = function () {
  36944. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36945. };
  36946. PlaneGeometry.prototype.copy = function (id) {
  36947. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36948. };
  36949. PlaneGeometry.prototype.serialize = function () {
  36950. var serializationObject = _super.prototype.serialize.call(this);
  36951. serializationObject.size = this.size;
  36952. return serializationObject;
  36953. };
  36954. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36955. if (scene.getGeometryByID(parsedPlane.id)) {
  36956. return null; // null since geometry could be something else than a ground...
  36957. }
  36958. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36959. if (BABYLON.Tags) {
  36960. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36961. }
  36962. scene.pushGeometry(plane, true);
  36963. return plane;
  36964. };
  36965. return PlaneGeometry;
  36966. }(_PrimitiveGeometry));
  36967. BABYLON.PlaneGeometry = PlaneGeometry;
  36968. /**
  36969. * Creates a torus knot geometry
  36970. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36971. */
  36972. var TorusKnotGeometry = /** @class */ (function (_super) {
  36973. __extends(TorusKnotGeometry, _super);
  36974. /**
  36975. * Creates a torus knot geometry
  36976. * @param id defines the unique ID of the geometry
  36977. * @param scene defines the hosting scene
  36978. * @param radius defines the radius of the torus knot
  36979. * @param tube defines the thickness of the torus knot tube
  36980. * @param radialSegments defines the number of radial segments
  36981. * @param tubularSegments defines the number of tubular segments
  36982. * @param p defines the first number of windings
  36983. * @param q defines the second number of windings
  36984. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36985. * @param mesh defines the hosting mesh (can be null)
  36986. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36987. */
  36988. function TorusKnotGeometry(id, scene,
  36989. /**
  36990. * Defines the radius of the torus knot
  36991. */
  36992. radius,
  36993. /**
  36994. * Defines the thickness of the torus knot tube
  36995. */
  36996. tube,
  36997. /**
  36998. * Defines the number of radial segments
  36999. */
  37000. radialSegments,
  37001. /**
  37002. * Defines the number of tubular segments
  37003. */
  37004. tubularSegments,
  37005. /**
  37006. * Defines the first number of windings
  37007. */
  37008. p,
  37009. /**
  37010. * Defines the second number of windings
  37011. */
  37012. q, canBeRegenerated, mesh,
  37013. /**
  37014. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37015. */
  37016. side) {
  37017. if (mesh === void 0) { mesh = null; }
  37018. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37019. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37020. _this.radius = radius;
  37021. _this.tube = tube;
  37022. _this.radialSegments = radialSegments;
  37023. _this.tubularSegments = tubularSegments;
  37024. _this.p = p;
  37025. _this.q = q;
  37026. _this.side = side;
  37027. return _this;
  37028. }
  37029. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37030. 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 });
  37031. };
  37032. TorusKnotGeometry.prototype.copy = function (id) {
  37033. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37034. };
  37035. TorusKnotGeometry.prototype.serialize = function () {
  37036. var serializationObject = _super.prototype.serialize.call(this);
  37037. serializationObject.radius = this.radius;
  37038. serializationObject.tube = this.tube;
  37039. serializationObject.radialSegments = this.radialSegments;
  37040. serializationObject.tubularSegments = this.tubularSegments;
  37041. serializationObject.p = this.p;
  37042. serializationObject.q = this.q;
  37043. return serializationObject;
  37044. };
  37045. ;
  37046. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37047. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37048. return null; // null since geometry could be something else than a ground...
  37049. }
  37050. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37051. if (BABYLON.Tags) {
  37052. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37053. }
  37054. scene.pushGeometry(torusKnot, true);
  37055. return torusKnot;
  37056. };
  37057. return TorusKnotGeometry;
  37058. }(_PrimitiveGeometry));
  37059. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37060. //}
  37061. })(BABYLON || (BABYLON = {}));
  37062. //# sourceMappingURL=babylon.geometry.js.map
  37063. "use strict";
  37064. var BABYLON;
  37065. (function (BABYLON) {
  37066. /**
  37067. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37068. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37069. */
  37070. var PostProcessManager = /** @class */ (function () {
  37071. /**
  37072. * Creates a new instance of @see PostProcess
  37073. * @param scene The scene that the post process is associated with.
  37074. */
  37075. function PostProcessManager(scene) {
  37076. this._vertexBuffers = {};
  37077. this._scene = scene;
  37078. }
  37079. PostProcessManager.prototype._prepareBuffers = function () {
  37080. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37081. return;
  37082. }
  37083. // VBO
  37084. var vertices = [];
  37085. vertices.push(1, 1);
  37086. vertices.push(-1, 1);
  37087. vertices.push(-1, -1);
  37088. vertices.push(1, -1);
  37089. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37090. this._buildIndexBuffer();
  37091. };
  37092. PostProcessManager.prototype._buildIndexBuffer = function () {
  37093. // Indices
  37094. var indices = [];
  37095. indices.push(0);
  37096. indices.push(1);
  37097. indices.push(2);
  37098. indices.push(0);
  37099. indices.push(2);
  37100. indices.push(3);
  37101. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37102. };
  37103. /**
  37104. * Rebuilds the vertex buffers of the manager.
  37105. */
  37106. PostProcessManager.prototype._rebuild = function () {
  37107. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37108. if (!vb) {
  37109. return;
  37110. }
  37111. vb._rebuild();
  37112. this._buildIndexBuffer();
  37113. };
  37114. // Methods
  37115. /**
  37116. * Prepares a frame to be run through a post process.
  37117. * @param sourceTexture The input texture to the post procesess. (default: null)
  37118. * @param postProcesses An array of post processes to be run. (default: null)
  37119. * @returns True if the post processes were able to be run.
  37120. */
  37121. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37122. if (sourceTexture === void 0) { sourceTexture = null; }
  37123. if (postProcesses === void 0) { postProcesses = null; }
  37124. var camera = this._scene.activeCamera;
  37125. if (!camera) {
  37126. return false;
  37127. }
  37128. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37129. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37130. return false;
  37131. }
  37132. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37133. return true;
  37134. };
  37135. /**
  37136. * Manually render a set of post processes to a texture.
  37137. * @param postProcesses An array of post processes to be run.
  37138. * @param targetTexture The target texture to render to.
  37139. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37140. */
  37141. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37142. if (targetTexture === void 0) { targetTexture = null; }
  37143. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37144. var engine = this._scene.getEngine();
  37145. for (var index = 0; index < postProcesses.length; index++) {
  37146. if (index < postProcesses.length - 1) {
  37147. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37148. }
  37149. else {
  37150. if (targetTexture) {
  37151. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37152. }
  37153. else {
  37154. engine.restoreDefaultFramebuffer();
  37155. }
  37156. }
  37157. var pp = postProcesses[index];
  37158. var effect = pp.apply();
  37159. if (effect) {
  37160. pp.onBeforeRenderObservable.notifyObservers(effect);
  37161. // VBOs
  37162. this._prepareBuffers();
  37163. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37164. // Draw order
  37165. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37166. pp.onAfterRenderObservable.notifyObservers(effect);
  37167. }
  37168. }
  37169. // Restore depth buffer
  37170. engine.setDepthBuffer(true);
  37171. engine.setDepthWrite(true);
  37172. };
  37173. /**
  37174. * Finalize the result of the output of the postprocesses.
  37175. * @param doNotPresent If true the result will not be displayed to the screen.
  37176. * @param targetTexture The target texture to render to.
  37177. * @param faceIndex The index of the face to bind the target texture to.
  37178. * @param postProcesses The array of post processes to render.
  37179. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37180. */
  37181. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37182. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37183. var camera = this._scene.activeCamera;
  37184. if (!camera) {
  37185. return;
  37186. }
  37187. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37188. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37189. return;
  37190. }
  37191. var engine = this._scene.getEngine();
  37192. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37193. var pp = postProcesses[index];
  37194. if (index < len - 1) {
  37195. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37196. }
  37197. else {
  37198. if (targetTexture) {
  37199. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37200. }
  37201. else {
  37202. engine.restoreDefaultFramebuffer();
  37203. }
  37204. }
  37205. if (doNotPresent) {
  37206. break;
  37207. }
  37208. var effect = pp.apply();
  37209. if (effect) {
  37210. pp.onBeforeRenderObservable.notifyObservers(effect);
  37211. // VBOs
  37212. this._prepareBuffers();
  37213. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37214. // Draw order
  37215. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37216. pp.onAfterRenderObservable.notifyObservers(effect);
  37217. }
  37218. }
  37219. // Restore states
  37220. engine.setDepthBuffer(true);
  37221. engine.setDepthWrite(true);
  37222. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37223. };
  37224. /**
  37225. * Disposes of the post process manager.
  37226. */
  37227. PostProcessManager.prototype.dispose = function () {
  37228. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37229. if (buffer) {
  37230. buffer.dispose();
  37231. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37232. }
  37233. if (this._indexBuffer) {
  37234. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37235. this._indexBuffer = null;
  37236. }
  37237. };
  37238. return PostProcessManager;
  37239. }());
  37240. BABYLON.PostProcessManager = PostProcessManager;
  37241. })(BABYLON || (BABYLON = {}));
  37242. //# sourceMappingURL=babylon.postProcessManager.js.map
  37243. "use strict";
  37244. var BABYLON;
  37245. (function (BABYLON) {
  37246. /**
  37247. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37248. */
  37249. var PerformanceMonitor = /** @class */ (function () {
  37250. /**
  37251. * constructor
  37252. * @param frameSampleSize The number of samples required to saturate the sliding window
  37253. */
  37254. function PerformanceMonitor(frameSampleSize) {
  37255. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37256. this._enabled = true;
  37257. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37258. }
  37259. /**
  37260. * Samples current frame
  37261. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37262. */
  37263. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37264. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37265. if (!this._enabled)
  37266. return;
  37267. if (this._lastFrameTimeMs != null) {
  37268. var dt = timeMs - this._lastFrameTimeMs;
  37269. this._rollingFrameTime.add(dt);
  37270. }
  37271. this._lastFrameTimeMs = timeMs;
  37272. };
  37273. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37274. /**
  37275. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37276. * @return Average frame time in milliseconds
  37277. */
  37278. get: function () {
  37279. return this._rollingFrameTime.average;
  37280. },
  37281. enumerable: true,
  37282. configurable: true
  37283. });
  37284. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37285. /**
  37286. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37287. * @return Frame time variance in milliseconds squared
  37288. */
  37289. get: function () {
  37290. return this._rollingFrameTime.variance;
  37291. },
  37292. enumerable: true,
  37293. configurable: true
  37294. });
  37295. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37296. /**
  37297. * Returns the frame time of the most recent frame
  37298. * @return Frame time in milliseconds
  37299. */
  37300. get: function () {
  37301. return this._rollingFrameTime.history(0);
  37302. },
  37303. enumerable: true,
  37304. configurable: true
  37305. });
  37306. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37307. /**
  37308. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37309. * @return Framerate in frames per second
  37310. */
  37311. get: function () {
  37312. return 1000.0 / this._rollingFrameTime.average;
  37313. },
  37314. enumerable: true,
  37315. configurable: true
  37316. });
  37317. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37318. /**
  37319. * Returns the average framerate in frames per second using the most recent frame time
  37320. * @return Framerate in frames per second
  37321. */
  37322. get: function () {
  37323. var history = this._rollingFrameTime.history(0);
  37324. if (history === 0) {
  37325. return 0;
  37326. }
  37327. return 1000.0 / history;
  37328. },
  37329. enumerable: true,
  37330. configurable: true
  37331. });
  37332. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37333. /**
  37334. * Returns true if enough samples have been taken to completely fill the sliding window
  37335. * @return true if saturated
  37336. */
  37337. get: function () {
  37338. return this._rollingFrameTime.isSaturated();
  37339. },
  37340. enumerable: true,
  37341. configurable: true
  37342. });
  37343. /**
  37344. * Enables contributions to the sliding window sample set
  37345. */
  37346. PerformanceMonitor.prototype.enable = function () {
  37347. this._enabled = true;
  37348. };
  37349. /**
  37350. * Disables contributions to the sliding window sample set
  37351. * Samples will not be interpolated over the disabled period
  37352. */
  37353. PerformanceMonitor.prototype.disable = function () {
  37354. this._enabled = false;
  37355. //clear last sample to avoid interpolating over the disabled period when next enabled
  37356. this._lastFrameTimeMs = null;
  37357. };
  37358. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37359. /**
  37360. * Returns true if sampling is enabled
  37361. * @return true if enabled
  37362. */
  37363. get: function () {
  37364. return this._enabled;
  37365. },
  37366. enumerable: true,
  37367. configurable: true
  37368. });
  37369. /**
  37370. * Resets performance monitor
  37371. */
  37372. PerformanceMonitor.prototype.reset = function () {
  37373. //clear last sample to avoid interpolating over the disabled period when next enabled
  37374. this._lastFrameTimeMs = null;
  37375. //wipe record
  37376. this._rollingFrameTime.reset();
  37377. };
  37378. return PerformanceMonitor;
  37379. }());
  37380. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37381. /**
  37382. * RollingAverage
  37383. *
  37384. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37385. */
  37386. var RollingAverage = /** @class */ (function () {
  37387. /**
  37388. * constructor
  37389. * @param length The number of samples required to saturate the sliding window
  37390. */
  37391. function RollingAverage(length) {
  37392. this._samples = new Array(length);
  37393. this.reset();
  37394. }
  37395. /**
  37396. * Adds a sample to the sample set
  37397. * @param v The sample value
  37398. */
  37399. RollingAverage.prototype.add = function (v) {
  37400. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37401. var delta;
  37402. //we need to check if we've already wrapped round
  37403. if (this.isSaturated()) {
  37404. //remove bottom of stack from mean
  37405. var bottomValue = this._samples[this._pos];
  37406. delta = bottomValue - this.average;
  37407. this.average -= delta / (this._sampleCount - 1);
  37408. this._m2 -= delta * (bottomValue - this.average);
  37409. }
  37410. else {
  37411. this._sampleCount++;
  37412. }
  37413. //add new value to mean
  37414. delta = v - this.average;
  37415. this.average += delta / (this._sampleCount);
  37416. this._m2 += delta * (v - this.average);
  37417. //set the new variance
  37418. this.variance = this._m2 / (this._sampleCount - 1);
  37419. this._samples[this._pos] = v;
  37420. this._pos++;
  37421. this._pos %= this._samples.length; //positive wrap around
  37422. };
  37423. /**
  37424. * Returns previously added values or null if outside of history or outside the sliding window domain
  37425. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37426. * @return Value previously recorded with add() or null if outside of range
  37427. */
  37428. RollingAverage.prototype.history = function (i) {
  37429. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37430. return 0;
  37431. }
  37432. var i0 = this._wrapPosition(this._pos - 1.0);
  37433. return this._samples[this._wrapPosition(i0 - i)];
  37434. };
  37435. /**
  37436. * Returns true if enough samples have been taken to completely fill the sliding window
  37437. * @return true if sample-set saturated
  37438. */
  37439. RollingAverage.prototype.isSaturated = function () {
  37440. return this._sampleCount >= this._samples.length;
  37441. };
  37442. /**
  37443. * Resets the rolling average (equivalent to 0 samples taken so far)
  37444. */
  37445. RollingAverage.prototype.reset = function () {
  37446. this.average = 0;
  37447. this.variance = 0;
  37448. this._sampleCount = 0;
  37449. this._pos = 0;
  37450. this._m2 = 0;
  37451. };
  37452. /**
  37453. * Wraps a value around the sample range boundaries
  37454. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37455. * @return Wrapped position in sample range
  37456. */
  37457. RollingAverage.prototype._wrapPosition = function (i) {
  37458. var max = this._samples.length;
  37459. return ((i % max) + max) % max;
  37460. };
  37461. return RollingAverage;
  37462. }());
  37463. BABYLON.RollingAverage = RollingAverage;
  37464. })(BABYLON || (BABYLON = {}));
  37465. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37466. "use strict";
  37467. var BABYLON;
  37468. (function (BABYLON) {
  37469. /**
  37470. * This groups together the common properties used for image processing either in direct forward pass
  37471. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37472. * or not.
  37473. */
  37474. var ImageProcessingConfiguration = /** @class */ (function () {
  37475. function ImageProcessingConfiguration() {
  37476. /**
  37477. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37478. */
  37479. this.colorCurves = new BABYLON.ColorCurves();
  37480. this._colorCurvesEnabled = false;
  37481. this._colorGradingEnabled = false;
  37482. this._colorGradingWithGreenDepth = true;
  37483. this._colorGradingBGR = true;
  37484. this._exposure = 1.0;
  37485. this._toneMappingEnabled = false;
  37486. this._contrast = 1.0;
  37487. /**
  37488. * Vignette stretch size.
  37489. */
  37490. this.vignetteStretch = 0;
  37491. /**
  37492. * Vignette centre X Offset.
  37493. */
  37494. this.vignetteCentreX = 0;
  37495. /**
  37496. * Vignette centre Y Offset.
  37497. */
  37498. this.vignetteCentreY = 0;
  37499. /**
  37500. * Vignette weight or intensity of the vignette effect.
  37501. */
  37502. this.vignetteWeight = 1.5;
  37503. /**
  37504. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37505. * if vignetteEnabled is set to true.
  37506. */
  37507. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37508. /**
  37509. * Camera field of view used by the Vignette effect.
  37510. */
  37511. this.vignetteCameraFov = 0.5;
  37512. this._grainEnabled = false;
  37513. this._grainIntensity = 30;
  37514. this._grainAnimated = false;
  37515. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37516. this._vignetteEnabled = false;
  37517. this._applyByPostProcess = false;
  37518. this._isEnabled = true;
  37519. /**
  37520. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37521. * @type {BABYLON.Observable}
  37522. */
  37523. this.onUpdateParameters = new BABYLON.Observable();
  37524. }
  37525. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37526. /**
  37527. * Gets wether the color curves effect is enabled.
  37528. */
  37529. get: function () {
  37530. return this._colorCurvesEnabled;
  37531. },
  37532. /**
  37533. * Sets wether the color curves effect is enabled.
  37534. */
  37535. set: function (value) {
  37536. if (this._colorCurvesEnabled === value) {
  37537. return;
  37538. }
  37539. this._colorCurvesEnabled = value;
  37540. this._updateParameters();
  37541. },
  37542. enumerable: true,
  37543. configurable: true
  37544. });
  37545. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37546. /**
  37547. * Gets wether the color grading effect is enabled.
  37548. */
  37549. get: function () {
  37550. return this._colorGradingEnabled;
  37551. },
  37552. /**
  37553. * Sets wether the color grading effect is enabled.
  37554. */
  37555. set: function (value) {
  37556. if (this._colorGradingEnabled === value) {
  37557. return;
  37558. }
  37559. this._colorGradingEnabled = value;
  37560. this._updateParameters();
  37561. },
  37562. enumerable: true,
  37563. configurable: true
  37564. });
  37565. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37566. /**
  37567. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37568. */
  37569. get: function () {
  37570. return this._colorGradingWithGreenDepth;
  37571. },
  37572. /**
  37573. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37574. */
  37575. set: function (value) {
  37576. if (this._colorGradingWithGreenDepth === value) {
  37577. return;
  37578. }
  37579. this._colorGradingWithGreenDepth = value;
  37580. this._updateParameters();
  37581. },
  37582. enumerable: true,
  37583. configurable: true
  37584. });
  37585. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37586. /**
  37587. * Gets wether the color grading texture contains BGR values.
  37588. */
  37589. get: function () {
  37590. return this._colorGradingBGR;
  37591. },
  37592. /**
  37593. * Sets wether the color grading texture contains BGR values.
  37594. */
  37595. set: function (value) {
  37596. if (this._colorGradingBGR === value) {
  37597. return;
  37598. }
  37599. this._colorGradingBGR = value;
  37600. this._updateParameters();
  37601. },
  37602. enumerable: true,
  37603. configurable: true
  37604. });
  37605. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37606. /**
  37607. * Gets the Exposure used in the effect.
  37608. */
  37609. get: function () {
  37610. return this._exposure;
  37611. },
  37612. /**
  37613. * Sets the Exposure used in the effect.
  37614. */
  37615. set: function (value) {
  37616. if (this._exposure === value) {
  37617. return;
  37618. }
  37619. this._exposure = value;
  37620. this._updateParameters();
  37621. },
  37622. enumerable: true,
  37623. configurable: true
  37624. });
  37625. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37626. /**
  37627. * Gets wether the tone mapping effect is enabled.
  37628. */
  37629. get: function () {
  37630. return this._toneMappingEnabled;
  37631. },
  37632. /**
  37633. * Sets wether the tone mapping effect is enabled.
  37634. */
  37635. set: function (value) {
  37636. if (this._toneMappingEnabled === value) {
  37637. return;
  37638. }
  37639. this._toneMappingEnabled = value;
  37640. this._updateParameters();
  37641. },
  37642. enumerable: true,
  37643. configurable: true
  37644. });
  37645. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37646. /**
  37647. * Gets the contrast used in the effect.
  37648. */
  37649. get: function () {
  37650. return this._contrast;
  37651. },
  37652. /**
  37653. * Sets the contrast used in the effect.
  37654. */
  37655. set: function (value) {
  37656. if (this._contrast === value) {
  37657. return;
  37658. }
  37659. this._contrast = value;
  37660. this._updateParameters();
  37661. },
  37662. enumerable: true,
  37663. configurable: true
  37664. });
  37665. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37666. /**
  37667. * If the grain effect should be enabled.
  37668. */
  37669. get: function () {
  37670. return this._grainEnabled;
  37671. },
  37672. set: function (value) {
  37673. if (this._grainEnabled === value) {
  37674. return;
  37675. }
  37676. this._grainEnabled = value;
  37677. this._updateParameters();
  37678. },
  37679. enumerable: true,
  37680. configurable: true
  37681. });
  37682. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37683. /**
  37684. * Amount of grain to be applied by the grain effect.
  37685. */
  37686. get: function () {
  37687. return this._grainIntensity;
  37688. },
  37689. set: function (value) {
  37690. if (this._grainIntensity === value) {
  37691. return;
  37692. }
  37693. this._grainIntensity = value;
  37694. },
  37695. enumerable: true,
  37696. configurable: true
  37697. });
  37698. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37699. /**
  37700. * If the grain effect should be animated.
  37701. */
  37702. get: function () {
  37703. return this._grainAnimated;
  37704. },
  37705. set: function (value) {
  37706. if (this._grainAnimated === value) {
  37707. return;
  37708. }
  37709. this._grainAnimated = value;
  37710. this._updateParameters();
  37711. },
  37712. enumerable: true,
  37713. configurable: true
  37714. });
  37715. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37716. /**
  37717. * Gets the vignette blend mode allowing different kind of effect.
  37718. */
  37719. get: function () {
  37720. return this._vignetteBlendMode;
  37721. },
  37722. /**
  37723. * Sets the vignette blend mode allowing different kind of effect.
  37724. */
  37725. set: function (value) {
  37726. if (this._vignetteBlendMode === value) {
  37727. return;
  37728. }
  37729. this._vignetteBlendMode = value;
  37730. this._updateParameters();
  37731. },
  37732. enumerable: true,
  37733. configurable: true
  37734. });
  37735. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37736. /**
  37737. * Gets wether the vignette effect is enabled.
  37738. */
  37739. get: function () {
  37740. return this._vignetteEnabled;
  37741. },
  37742. /**
  37743. * Sets wether the vignette effect is enabled.
  37744. */
  37745. set: function (value) {
  37746. if (this._vignetteEnabled === value) {
  37747. return;
  37748. }
  37749. this._vignetteEnabled = value;
  37750. this._updateParameters();
  37751. },
  37752. enumerable: true,
  37753. configurable: true
  37754. });
  37755. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37756. /**
  37757. * Gets wether the image processing is applied through a post process or not.
  37758. */
  37759. get: function () {
  37760. return this._applyByPostProcess;
  37761. },
  37762. /**
  37763. * Sets wether the image processing is applied through a post process or not.
  37764. */
  37765. set: function (value) {
  37766. if (this._applyByPostProcess === value) {
  37767. return;
  37768. }
  37769. this._applyByPostProcess = value;
  37770. this._updateParameters();
  37771. },
  37772. enumerable: true,
  37773. configurable: true
  37774. });
  37775. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37776. /**
  37777. * Gets wether the image processing is enabled or not.
  37778. */
  37779. get: function () {
  37780. return this._isEnabled;
  37781. },
  37782. /**
  37783. * Sets wether the image processing is enabled or not.
  37784. */
  37785. set: function (value) {
  37786. if (this._isEnabled === value) {
  37787. return;
  37788. }
  37789. this._isEnabled = value;
  37790. this._updateParameters();
  37791. },
  37792. enumerable: true,
  37793. configurable: true
  37794. });
  37795. /**
  37796. * Method called each time the image processing information changes requires to recompile the effect.
  37797. */
  37798. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37799. this.onUpdateParameters.notifyObservers(this);
  37800. };
  37801. ImageProcessingConfiguration.prototype.getClassName = function () {
  37802. return "ImageProcessingConfiguration";
  37803. };
  37804. /**
  37805. * Prepare the list of uniforms associated with the Image Processing effects.
  37806. * @param uniformsList The list of uniforms used in the effect
  37807. * @param defines the list of defines currently in use
  37808. */
  37809. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37810. if (defines.EXPOSURE) {
  37811. uniforms.push("exposureLinear");
  37812. }
  37813. if (defines.CONTRAST) {
  37814. uniforms.push("contrast");
  37815. }
  37816. if (defines.COLORGRADING) {
  37817. uniforms.push("colorTransformSettings");
  37818. }
  37819. if (defines.VIGNETTE) {
  37820. uniforms.push("vInverseScreenSize");
  37821. uniforms.push("vignetteSettings1");
  37822. uniforms.push("vignetteSettings2");
  37823. }
  37824. if (defines.COLORCURVES) {
  37825. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37826. }
  37827. if (defines.GRAIN) {
  37828. uniforms.push("grainVarianceAmount");
  37829. uniforms.push("grainAnimatedSeed");
  37830. }
  37831. };
  37832. /**
  37833. * Prepare the list of samplers associated with the Image Processing effects.
  37834. * @param uniformsList The list of uniforms used in the effect
  37835. * @param defines the list of defines currently in use
  37836. */
  37837. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37838. if (defines.COLORGRADING) {
  37839. samplersList.push("txColorTransform");
  37840. }
  37841. };
  37842. /**
  37843. * Prepare the list of defines associated to the shader.
  37844. * @param defines the list of defines to complete
  37845. */
  37846. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37847. if (forPostProcess === void 0) { forPostProcess = false; }
  37848. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37849. defines.VIGNETTE = false;
  37850. defines.TONEMAPPING = false;
  37851. defines.CONTRAST = false;
  37852. defines.EXPOSURE = false;
  37853. defines.COLORCURVES = false;
  37854. defines.COLORGRADING = false;
  37855. defines.COLORGRADING3D = false;
  37856. defines.IMAGEPROCESSING = false;
  37857. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37858. return;
  37859. }
  37860. defines.VIGNETTE = this.vignetteEnabled;
  37861. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37862. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37863. defines.TONEMAPPING = this.toneMappingEnabled;
  37864. defines.CONTRAST = (this.contrast !== 1.0);
  37865. defines.EXPOSURE = (this.exposure !== 1.0);
  37866. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37867. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37868. if (defines.COLORGRADING) {
  37869. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37870. }
  37871. else {
  37872. defines.COLORGRADING3D = false;
  37873. }
  37874. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37875. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37876. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37877. defines.GRAIN = this.grainEnabled;
  37878. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37879. };
  37880. /**
  37881. * Returns true if all the image processing information are ready.
  37882. */
  37883. ImageProcessingConfiguration.prototype.isReady = function () {
  37884. // Color Grading texure can not be none blocking.
  37885. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37886. };
  37887. /**
  37888. * Binds the image processing to the shader.
  37889. * @param effect The effect to bind to
  37890. */
  37891. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37892. if (aspectRatio === void 0) { aspectRatio = 1; }
  37893. // Color Curves
  37894. if (this._colorCurvesEnabled && this.colorCurves) {
  37895. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37896. }
  37897. // Vignette
  37898. if (this._vignetteEnabled) {
  37899. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37900. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37901. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37902. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37903. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37904. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37905. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37906. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37907. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37908. var vignettePower = -2.0 * this.vignetteWeight;
  37909. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37910. }
  37911. // Exposure
  37912. effect.setFloat("exposureLinear", this.exposure);
  37913. // Contrast
  37914. effect.setFloat("contrast", this.contrast);
  37915. // Color transform settings
  37916. if (this.colorGradingTexture) {
  37917. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37918. var textureSize = this.colorGradingTexture.getSize().height;
  37919. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37920. 0.5 / textureSize, // textureOffset
  37921. textureSize, // textureSize
  37922. this.colorGradingTexture.level // weight
  37923. );
  37924. }
  37925. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37926. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37927. };
  37928. /**
  37929. * Clones the current image processing instance.
  37930. * @return The cloned image processing
  37931. */
  37932. ImageProcessingConfiguration.prototype.clone = function () {
  37933. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37934. };
  37935. /**
  37936. * Serializes the current image processing instance to a json representation.
  37937. * @return a JSON representation
  37938. */
  37939. ImageProcessingConfiguration.prototype.serialize = function () {
  37940. return BABYLON.SerializationHelper.Serialize(this);
  37941. };
  37942. /**
  37943. * Parses the image processing from a json representation.
  37944. * @param source the JSON source to parse
  37945. * @return The parsed image processing
  37946. */
  37947. ImageProcessingConfiguration.Parse = function (source) {
  37948. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37949. };
  37950. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37951. /**
  37952. * Used to apply the vignette as a mix with the pixel color.
  37953. */
  37954. get: function () {
  37955. return this._VIGNETTEMODE_MULTIPLY;
  37956. },
  37957. enumerable: true,
  37958. configurable: true
  37959. });
  37960. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37961. /**
  37962. * Used to apply the vignette as a replacement of the pixel color.
  37963. */
  37964. get: function () {
  37965. return this._VIGNETTEMODE_OPAQUE;
  37966. },
  37967. enumerable: true,
  37968. configurable: true
  37969. });
  37970. // Static constants associated to the image processing.
  37971. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37972. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37973. __decorate([
  37974. BABYLON.serializeAsColorCurves()
  37975. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37976. __decorate([
  37977. BABYLON.serialize()
  37978. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37979. __decorate([
  37980. BABYLON.serializeAsTexture()
  37981. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37982. __decorate([
  37983. BABYLON.serialize()
  37984. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37985. __decorate([
  37986. BABYLON.serialize()
  37987. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37988. __decorate([
  37989. BABYLON.serialize()
  37990. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37991. __decorate([
  37992. BABYLON.serialize()
  37993. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37994. __decorate([
  37995. BABYLON.serialize()
  37996. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37997. __decorate([
  37998. BABYLON.serialize()
  37999. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  38000. __decorate([
  38001. BABYLON.serialize()
  38002. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  38003. __decorate([
  38004. BABYLON.serialize()
  38005. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  38006. __decorate([
  38007. BABYLON.serialize()
  38008. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38009. __decorate([
  38010. BABYLON.serialize()
  38011. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38012. __decorate([
  38013. BABYLON.serializeAsColor4()
  38014. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38015. __decorate([
  38016. BABYLON.serialize()
  38017. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38018. __decorate([
  38019. BABYLON.serialize()
  38020. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  38021. __decorate([
  38022. BABYLON.serialize()
  38023. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  38024. __decorate([
  38025. BABYLON.serialize()
  38026. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  38027. __decorate([
  38028. BABYLON.serialize()
  38029. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38030. __decorate([
  38031. BABYLON.serialize()
  38032. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38033. __decorate([
  38034. BABYLON.serialize()
  38035. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38036. __decorate([
  38037. BABYLON.serialize()
  38038. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38039. return ImageProcessingConfiguration;
  38040. }());
  38041. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38042. })(BABYLON || (BABYLON = {}));
  38043. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38044. "use strict";
  38045. var BABYLON;
  38046. (function (BABYLON) {
  38047. /**
  38048. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38049. * It can help converting any input color in a desired output one. This can then be used to create effects
  38050. * from sepia, black and white to sixties or futuristic rendering...
  38051. *
  38052. * The only supported format is currently 3dl.
  38053. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38054. */
  38055. var ColorGradingTexture = /** @class */ (function (_super) {
  38056. __extends(ColorGradingTexture, _super);
  38057. /**
  38058. * Instantiates a ColorGradingTexture from the following parameters.
  38059. *
  38060. * @param url The location of the color gradind data (currently only supporting 3dl)
  38061. * @param scene The scene the texture will be used in
  38062. */
  38063. function ColorGradingTexture(url, scene) {
  38064. var _this = _super.call(this, scene) || this;
  38065. if (!url) {
  38066. return _this;
  38067. }
  38068. _this._engine = scene.getEngine();
  38069. _this._textureMatrix = BABYLON.Matrix.Identity();
  38070. _this.name = url;
  38071. _this.url = url;
  38072. _this.hasAlpha = false;
  38073. _this.isCube = false;
  38074. _this.is3D = _this._engine.webGLVersion > 1;
  38075. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38076. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38077. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38078. _this.anisotropicFilteringLevel = 1;
  38079. _this._texture = _this._getFromCache(url, true);
  38080. if (!_this._texture) {
  38081. if (!scene.useDelayedTextureLoading) {
  38082. _this.loadTexture();
  38083. }
  38084. else {
  38085. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38086. }
  38087. }
  38088. return _this;
  38089. }
  38090. /**
  38091. * Returns the texture matrix used in most of the material.
  38092. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38093. */
  38094. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38095. return this._textureMatrix;
  38096. };
  38097. /**
  38098. * Occurs when the file being loaded is a .3dl LUT file.
  38099. */
  38100. ColorGradingTexture.prototype.load3dlTexture = function () {
  38101. var engine = this._engine;
  38102. var texture;
  38103. if (engine.webGLVersion === 1) {
  38104. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38105. }
  38106. else {
  38107. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38108. }
  38109. this._texture = texture;
  38110. var callback = function (text) {
  38111. if (typeof text !== "string") {
  38112. return;
  38113. }
  38114. var data = null;
  38115. var tempData = null;
  38116. var line;
  38117. var lines = text.split('\n');
  38118. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38119. var maxColor = 0;
  38120. for (var i = 0; i < lines.length; i++) {
  38121. line = lines[i];
  38122. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38123. continue;
  38124. if (line.indexOf('#') === 0)
  38125. continue;
  38126. var words = line.split(" ");
  38127. if (size === 0) {
  38128. // Number of space + one
  38129. size = words.length;
  38130. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38131. tempData = new Float32Array(size * size * size * 4);
  38132. continue;
  38133. }
  38134. if (size != 0) {
  38135. var r = Math.max(parseInt(words[0]), 0);
  38136. var g = Math.max(parseInt(words[1]), 0);
  38137. var b = Math.max(parseInt(words[2]), 0);
  38138. maxColor = Math.max(r, maxColor);
  38139. maxColor = Math.max(g, maxColor);
  38140. maxColor = Math.max(b, maxColor);
  38141. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38142. if (tempData) {
  38143. tempData[pixelStorageIndex + 0] = r;
  38144. tempData[pixelStorageIndex + 1] = g;
  38145. tempData[pixelStorageIndex + 2] = b;
  38146. }
  38147. pixelIndexSlice++;
  38148. if (pixelIndexSlice % size == 0) {
  38149. pixelIndexH++;
  38150. pixelIndexSlice = 0;
  38151. if (pixelIndexH % size == 0) {
  38152. pixelIndexW++;
  38153. pixelIndexH = 0;
  38154. }
  38155. }
  38156. }
  38157. }
  38158. if (tempData && data) {
  38159. for (var i = 0; i < tempData.length; i++) {
  38160. if (i > 0 && (i + 1) % 4 === 0) {
  38161. data[i] = 255;
  38162. }
  38163. else {
  38164. var value = tempData[i];
  38165. data[i] = (value / maxColor * 255);
  38166. }
  38167. }
  38168. }
  38169. if (texture.is3D) {
  38170. texture.updateSize(size, size, size);
  38171. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38172. }
  38173. else {
  38174. texture.updateSize(size * size, size);
  38175. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38176. }
  38177. };
  38178. var scene = this.getScene();
  38179. if (scene) {
  38180. scene._loadFile(this.url, callback);
  38181. }
  38182. else {
  38183. this._engine._loadFile(this.url, callback);
  38184. }
  38185. return this._texture;
  38186. };
  38187. /**
  38188. * Starts the loading process of the texture.
  38189. */
  38190. ColorGradingTexture.prototype.loadTexture = function () {
  38191. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38192. this.load3dlTexture();
  38193. }
  38194. };
  38195. /**
  38196. * Clones the color gradind texture.
  38197. */
  38198. ColorGradingTexture.prototype.clone = function () {
  38199. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38200. // Base texture
  38201. newTexture.level = this.level;
  38202. return newTexture;
  38203. };
  38204. /**
  38205. * Called during delayed load for textures.
  38206. */
  38207. ColorGradingTexture.prototype.delayLoad = function () {
  38208. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38209. return;
  38210. }
  38211. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38212. this._texture = this._getFromCache(this.url, true);
  38213. if (!this._texture) {
  38214. this.loadTexture();
  38215. }
  38216. };
  38217. /**
  38218. * Parses a color grading texture serialized by Babylon.
  38219. * @param parsedTexture The texture information being parsedTexture
  38220. * @param scene The scene to load the texture in
  38221. * @param rootUrl The root url of the data assets to load
  38222. * @return A color gradind texture
  38223. */
  38224. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38225. var texture = null;
  38226. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38227. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38228. texture.name = parsedTexture.name;
  38229. texture.level = parsedTexture.level;
  38230. }
  38231. return texture;
  38232. };
  38233. /**
  38234. * Serializes the LUT texture to json format.
  38235. */
  38236. ColorGradingTexture.prototype.serialize = function () {
  38237. if (!this.name) {
  38238. return null;
  38239. }
  38240. var serializationObject = {};
  38241. serializationObject.name = this.name;
  38242. serializationObject.level = this.level;
  38243. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38244. return serializationObject;
  38245. };
  38246. /**
  38247. * Empty line regex stored for GC.
  38248. */
  38249. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38250. return ColorGradingTexture;
  38251. }(BABYLON.BaseTexture));
  38252. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38253. })(BABYLON || (BABYLON = {}));
  38254. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38255. "use strict";
  38256. var BABYLON;
  38257. (function (BABYLON) {
  38258. /**
  38259. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38260. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38261. * 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;
  38262. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38263. */
  38264. var ColorCurves = /** @class */ (function () {
  38265. function ColorCurves() {
  38266. this._dirty = true;
  38267. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38268. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38269. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38270. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38271. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38272. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38273. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38274. this._globalHue = 30;
  38275. this._globalDensity = 0;
  38276. this._globalSaturation = 0;
  38277. this._globalExposure = 0;
  38278. this._highlightsHue = 30;
  38279. this._highlightsDensity = 0;
  38280. this._highlightsSaturation = 0;
  38281. this._highlightsExposure = 0;
  38282. this._midtonesHue = 30;
  38283. this._midtonesDensity = 0;
  38284. this._midtonesSaturation = 0;
  38285. this._midtonesExposure = 0;
  38286. this._shadowsHue = 30;
  38287. this._shadowsDensity = 0;
  38288. this._shadowsSaturation = 0;
  38289. this._shadowsExposure = 0;
  38290. }
  38291. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38292. /**
  38293. * Gets the global Hue value.
  38294. * 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).
  38295. */
  38296. get: function () {
  38297. return this._globalHue;
  38298. },
  38299. /**
  38300. * Sets the global Hue value.
  38301. * 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).
  38302. */
  38303. set: function (value) {
  38304. this._globalHue = value;
  38305. this._dirty = true;
  38306. },
  38307. enumerable: true,
  38308. configurable: true
  38309. });
  38310. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38311. /**
  38312. * Gets the global Density value.
  38313. * 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.
  38314. * Values less than zero provide a filter of opposite hue.
  38315. */
  38316. get: function () {
  38317. return this._globalDensity;
  38318. },
  38319. /**
  38320. * Sets the global Density value.
  38321. * 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.
  38322. * Values less than zero provide a filter of opposite hue.
  38323. */
  38324. set: function (value) {
  38325. this._globalDensity = value;
  38326. this._dirty = true;
  38327. },
  38328. enumerable: true,
  38329. configurable: true
  38330. });
  38331. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38332. /**
  38333. * Gets the global Saturation value.
  38334. * 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.
  38335. */
  38336. get: function () {
  38337. return this._globalSaturation;
  38338. },
  38339. /**
  38340. * Sets the global Saturation value.
  38341. * 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.
  38342. */
  38343. set: function (value) {
  38344. this._globalSaturation = value;
  38345. this._dirty = true;
  38346. },
  38347. enumerable: true,
  38348. configurable: true
  38349. });
  38350. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38351. /**
  38352. * Gets the highlights Hue value.
  38353. * 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).
  38354. */
  38355. get: function () {
  38356. return this._highlightsHue;
  38357. },
  38358. /**
  38359. * Sets the highlights Hue value.
  38360. * 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).
  38361. */
  38362. set: function (value) {
  38363. this._highlightsHue = value;
  38364. this._dirty = true;
  38365. },
  38366. enumerable: true,
  38367. configurable: true
  38368. });
  38369. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38370. /**
  38371. * Gets the highlights Density value.
  38372. * 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.
  38373. * Values less than zero provide a filter of opposite hue.
  38374. */
  38375. get: function () {
  38376. return this._highlightsDensity;
  38377. },
  38378. /**
  38379. * Sets the highlights Density value.
  38380. * 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.
  38381. * Values less than zero provide a filter of opposite hue.
  38382. */
  38383. set: function (value) {
  38384. this._highlightsDensity = value;
  38385. this._dirty = true;
  38386. },
  38387. enumerable: true,
  38388. configurable: true
  38389. });
  38390. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38391. /**
  38392. * Gets the highlights Saturation value.
  38393. * 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.
  38394. */
  38395. get: function () {
  38396. return this._highlightsSaturation;
  38397. },
  38398. /**
  38399. * Sets the highlights Saturation value.
  38400. * 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.
  38401. */
  38402. set: function (value) {
  38403. this._highlightsSaturation = value;
  38404. this._dirty = true;
  38405. },
  38406. enumerable: true,
  38407. configurable: true
  38408. });
  38409. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38410. /**
  38411. * Gets the highlights Exposure value.
  38412. * 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.
  38413. */
  38414. get: function () {
  38415. return this._highlightsExposure;
  38416. },
  38417. /**
  38418. * Sets the highlights Exposure value.
  38419. * 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.
  38420. */
  38421. set: function (value) {
  38422. this._highlightsExposure = value;
  38423. this._dirty = true;
  38424. },
  38425. enumerable: true,
  38426. configurable: true
  38427. });
  38428. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38429. /**
  38430. * Gets the midtones Hue value.
  38431. * 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).
  38432. */
  38433. get: function () {
  38434. return this._midtonesHue;
  38435. },
  38436. /**
  38437. * Sets the midtones Hue value.
  38438. * 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).
  38439. */
  38440. set: function (value) {
  38441. this._midtonesHue = value;
  38442. this._dirty = true;
  38443. },
  38444. enumerable: true,
  38445. configurable: true
  38446. });
  38447. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38448. /**
  38449. * Gets the midtones Density value.
  38450. * 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.
  38451. * Values less than zero provide a filter of opposite hue.
  38452. */
  38453. get: function () {
  38454. return this._midtonesDensity;
  38455. },
  38456. /**
  38457. * Sets the midtones Density value.
  38458. * 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.
  38459. * Values less than zero provide a filter of opposite hue.
  38460. */
  38461. set: function (value) {
  38462. this._midtonesDensity = value;
  38463. this._dirty = true;
  38464. },
  38465. enumerable: true,
  38466. configurable: true
  38467. });
  38468. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38469. /**
  38470. * Gets the midtones Saturation value.
  38471. * 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.
  38472. */
  38473. get: function () {
  38474. return this._midtonesSaturation;
  38475. },
  38476. /**
  38477. * Sets the midtones Saturation value.
  38478. * 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.
  38479. */
  38480. set: function (value) {
  38481. this._midtonesSaturation = value;
  38482. this._dirty = true;
  38483. },
  38484. enumerable: true,
  38485. configurable: true
  38486. });
  38487. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38488. /**
  38489. * Gets the midtones Exposure value.
  38490. * 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.
  38491. */
  38492. get: function () {
  38493. return this._midtonesExposure;
  38494. },
  38495. /**
  38496. * Sets the midtones Exposure value.
  38497. * 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.
  38498. */
  38499. set: function (value) {
  38500. this._midtonesExposure = value;
  38501. this._dirty = true;
  38502. },
  38503. enumerable: true,
  38504. configurable: true
  38505. });
  38506. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38507. /**
  38508. * Gets the shadows Hue value.
  38509. * 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).
  38510. */
  38511. get: function () {
  38512. return this._shadowsHue;
  38513. },
  38514. /**
  38515. * Sets the shadows Hue value.
  38516. * 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).
  38517. */
  38518. set: function (value) {
  38519. this._shadowsHue = value;
  38520. this._dirty = true;
  38521. },
  38522. enumerable: true,
  38523. configurable: true
  38524. });
  38525. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38526. /**
  38527. * Gets the shadows Density value.
  38528. * 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.
  38529. * Values less than zero provide a filter of opposite hue.
  38530. */
  38531. get: function () {
  38532. return this._shadowsDensity;
  38533. },
  38534. /**
  38535. * Sets the shadows Density value.
  38536. * 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.
  38537. * Values less than zero provide a filter of opposite hue.
  38538. */
  38539. set: function (value) {
  38540. this._shadowsDensity = value;
  38541. this._dirty = true;
  38542. },
  38543. enumerable: true,
  38544. configurable: true
  38545. });
  38546. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38547. /**
  38548. * Gets the shadows Saturation value.
  38549. * 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.
  38550. */
  38551. get: function () {
  38552. return this._shadowsSaturation;
  38553. },
  38554. /**
  38555. * Sets the shadows Saturation value.
  38556. * 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.
  38557. */
  38558. set: function (value) {
  38559. this._shadowsSaturation = value;
  38560. this._dirty = true;
  38561. },
  38562. enumerable: true,
  38563. configurable: true
  38564. });
  38565. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38566. /**
  38567. * Gets the shadows Exposure value.
  38568. * 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.
  38569. */
  38570. get: function () {
  38571. return this._shadowsExposure;
  38572. },
  38573. /**
  38574. * Sets the shadows Exposure value.
  38575. * 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.
  38576. */
  38577. set: function (value) {
  38578. this._shadowsExposure = value;
  38579. this._dirty = true;
  38580. },
  38581. enumerable: true,
  38582. configurable: true
  38583. });
  38584. ColorCurves.prototype.getClassName = function () {
  38585. return "ColorCurves";
  38586. };
  38587. /**
  38588. * Binds the color curves to the shader.
  38589. * @param colorCurves The color curve to bind
  38590. * @param effect The effect to bind to
  38591. */
  38592. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38593. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38594. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38595. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38596. if (colorCurves._dirty) {
  38597. colorCurves._dirty = false;
  38598. // Fill in global info.
  38599. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38600. // Compute highlights info.
  38601. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38602. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38603. // Compute midtones info.
  38604. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38605. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38606. // Compute shadows info.
  38607. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38608. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38609. // Compute deltas (neutral is midtones).
  38610. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38611. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38612. }
  38613. if (effect) {
  38614. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38615. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38616. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38617. }
  38618. };
  38619. /**
  38620. * Prepare the list of uniforms associated with the ColorCurves effects.
  38621. * @param uniformsList The list of uniforms used in the effect
  38622. */
  38623. ColorCurves.PrepareUniforms = function (uniformsList) {
  38624. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38625. };
  38626. /**
  38627. * Returns color grading data based on a hue, density, saturation and exposure value.
  38628. * @param filterHue The hue of the color filter.
  38629. * @param filterDensity The density of the color filter.
  38630. * @param saturation The saturation.
  38631. * @param exposure The exposure.
  38632. * @param result The result data container.
  38633. */
  38634. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38635. if (hue == null) {
  38636. return;
  38637. }
  38638. hue = ColorCurves.clamp(hue, 0, 360);
  38639. density = ColorCurves.clamp(density, -100, 100);
  38640. saturation = ColorCurves.clamp(saturation, -100, 100);
  38641. exposure = ColorCurves.clamp(exposure, -100, 100);
  38642. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38643. // so that the maximum filter density is only 50% control. This provides fine control
  38644. // for small values and reasonable range.
  38645. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38646. density *= 0.5;
  38647. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38648. if (density < 0) {
  38649. density *= -1;
  38650. hue = (hue + 180) % 360;
  38651. }
  38652. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38653. result.scaleToRef(2, result);
  38654. result.a = 1 + 0.01 * saturation;
  38655. };
  38656. /**
  38657. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38658. * @param value The input slider value in range [-100,100].
  38659. * @returns Adjusted value.
  38660. */
  38661. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38662. value /= 100;
  38663. var x = Math.abs(value);
  38664. x = Math.pow(x, 2);
  38665. if (value < 0) {
  38666. x *= -1;
  38667. }
  38668. x *= 100;
  38669. return x;
  38670. };
  38671. /**
  38672. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38673. * @param hue The hue (H) input.
  38674. * @param saturation The saturation (S) input.
  38675. * @param brightness The brightness (B) input.
  38676. * @result An RGBA color represented as Vector4.
  38677. */
  38678. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38679. var h = ColorCurves.clamp(hue, 0, 360);
  38680. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38681. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38682. if (s === 0) {
  38683. result.r = v;
  38684. result.g = v;
  38685. result.b = v;
  38686. }
  38687. else {
  38688. // sector 0 to 5
  38689. h /= 60;
  38690. var i = Math.floor(h);
  38691. // fractional part of h
  38692. var f = h - i;
  38693. var p = v * (1 - s);
  38694. var q = v * (1 - s * f);
  38695. var t = v * (1 - s * (1 - f));
  38696. switch (i) {
  38697. case 0:
  38698. result.r = v;
  38699. result.g = t;
  38700. result.b = p;
  38701. break;
  38702. case 1:
  38703. result.r = q;
  38704. result.g = v;
  38705. result.b = p;
  38706. break;
  38707. case 2:
  38708. result.r = p;
  38709. result.g = v;
  38710. result.b = t;
  38711. break;
  38712. case 3:
  38713. result.r = p;
  38714. result.g = q;
  38715. result.b = v;
  38716. break;
  38717. case 4:
  38718. result.r = t;
  38719. result.g = p;
  38720. result.b = v;
  38721. break;
  38722. default:// case 5:
  38723. result.r = v;
  38724. result.g = p;
  38725. result.b = q;
  38726. break;
  38727. }
  38728. }
  38729. result.a = 1;
  38730. };
  38731. /**
  38732. * Returns a value clamped between min and max
  38733. * @param value The value to clamp
  38734. * @param min The minimum of value
  38735. * @param max The maximum of value
  38736. * @returns The clamped value.
  38737. */
  38738. ColorCurves.clamp = function (value, min, max) {
  38739. return Math.min(Math.max(value, min), max);
  38740. };
  38741. /**
  38742. * Clones the current color curve instance.
  38743. * @return The cloned curves
  38744. */
  38745. ColorCurves.prototype.clone = function () {
  38746. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38747. };
  38748. /**
  38749. * Serializes the current color curve instance to a json representation.
  38750. * @return a JSON representation
  38751. */
  38752. ColorCurves.prototype.serialize = function () {
  38753. return BABYLON.SerializationHelper.Serialize(this);
  38754. };
  38755. /**
  38756. * Parses the color curve from a json representation.
  38757. * @param source the JSON source to parse
  38758. * @return The parsed curves
  38759. */
  38760. ColorCurves.Parse = function (source) {
  38761. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38762. };
  38763. __decorate([
  38764. BABYLON.serialize()
  38765. ], ColorCurves.prototype, "_globalHue", void 0);
  38766. __decorate([
  38767. BABYLON.serialize()
  38768. ], ColorCurves.prototype, "_globalDensity", void 0);
  38769. __decorate([
  38770. BABYLON.serialize()
  38771. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38772. __decorate([
  38773. BABYLON.serialize()
  38774. ], ColorCurves.prototype, "_globalExposure", void 0);
  38775. __decorate([
  38776. BABYLON.serialize()
  38777. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38778. __decorate([
  38779. BABYLON.serialize()
  38780. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38781. __decorate([
  38782. BABYLON.serialize()
  38783. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38784. __decorate([
  38785. BABYLON.serialize()
  38786. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38787. __decorate([
  38788. BABYLON.serialize()
  38789. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38790. __decorate([
  38791. BABYLON.serialize()
  38792. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38793. __decorate([
  38794. BABYLON.serialize()
  38795. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38796. __decorate([
  38797. BABYLON.serialize()
  38798. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38799. return ColorCurves;
  38800. }());
  38801. BABYLON.ColorCurves = ColorCurves;
  38802. })(BABYLON || (BABYLON = {}));
  38803. //# sourceMappingURL=babylon.colorCurves.js.map
  38804. "use strict";
  38805. //# sourceMappingURL=babylon.behavior.js.map
  38806. "use strict";
  38807. var BABYLON;
  38808. (function (BABYLON) {
  38809. /**
  38810. * "Static Class" containing the most commonly used helper while dealing with material for
  38811. * rendering purpose.
  38812. *
  38813. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38814. *
  38815. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38816. */
  38817. var MaterialHelper = /** @class */ (function () {
  38818. function MaterialHelper() {
  38819. }
  38820. /**
  38821. * Bind the current view position to an effect.
  38822. * @param effect The effect to be bound
  38823. * @param scene The scene the eyes position is used from
  38824. */
  38825. MaterialHelper.BindEyePosition = function (effect, scene) {
  38826. if (scene._forcedViewPosition) {
  38827. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38828. return;
  38829. }
  38830. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38831. };
  38832. /**
  38833. * Helps preparing the defines values about the UVs in used in the effect.
  38834. * UVs are shared as much as we can accross chanels in the shaders.
  38835. * @param texture The texture we are preparing the UVs for
  38836. * @param defines The defines to update
  38837. * @param key The chanel key "diffuse", "specular"... used in the shader
  38838. */
  38839. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38840. defines._needUVs = true;
  38841. defines[key] = true;
  38842. if (texture.getTextureMatrix().isIdentity(true)) {
  38843. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38844. if (texture.coordinatesIndex === 0) {
  38845. defines["MAINUV1"] = true;
  38846. }
  38847. else {
  38848. defines["MAINUV2"] = true;
  38849. }
  38850. }
  38851. else {
  38852. defines[key + "DIRECTUV"] = 0;
  38853. }
  38854. };
  38855. /**
  38856. * Binds a texture matrix value to its corrsponding uniform
  38857. * @param texture The texture to bind the matrix for
  38858. * @param uniformBuffer The uniform buffer receivin the data
  38859. * @param key The chanel key "diffuse", "specular"... used in the shader
  38860. */
  38861. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38862. var matrix = texture.getTextureMatrix();
  38863. if (!matrix.isIdentity(true)) {
  38864. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38865. }
  38866. };
  38867. /**
  38868. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38869. * @param mesh defines the current mesh
  38870. * @param scene defines the current scene
  38871. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38872. * @param pointsCloud defines if point cloud rendering has to be turned on
  38873. * @param fogEnabled defines if fog has to be turned on
  38874. * @param alphaTest defines if alpha testing has to be turned on
  38875. * @param defines defines the current list of defines
  38876. */
  38877. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38878. if (defines._areMiscDirty) {
  38879. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38880. defines["POINTSIZE"] = pointsCloud;
  38881. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38882. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38883. defines["ALPHATEST"] = alphaTest;
  38884. }
  38885. };
  38886. /**
  38887. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38888. * @param scene defines the current scene
  38889. * @param engine defines the current engine
  38890. * @param defines specifies the list of active defines
  38891. * @param useInstances defines if instances have to be turned on
  38892. * @param useClipPlane defines if clip plane have to be turned on
  38893. */
  38894. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38895. if (useClipPlane === void 0) { useClipPlane = null; }
  38896. var changed = false;
  38897. if (useClipPlane == null) {
  38898. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38899. }
  38900. if (defines["CLIPPLANE"] !== useClipPlane) {
  38901. defines["CLIPPLANE"] = useClipPlane;
  38902. changed = true;
  38903. }
  38904. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38905. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38906. changed = true;
  38907. }
  38908. if (defines["INSTANCES"] !== useInstances) {
  38909. defines["INSTANCES"] = useInstances;
  38910. changed = true;
  38911. }
  38912. if (changed) {
  38913. defines.markAsUnprocessed();
  38914. }
  38915. };
  38916. /**
  38917. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38918. * @param mesh The mesh containing the geometry data we will draw
  38919. * @param defines The defines to update
  38920. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38921. * @param useBones Precise whether bones should be used or not (override mesh info)
  38922. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38923. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38924. * @returns false if defines are considered not dirty and have not been checked
  38925. */
  38926. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38927. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38928. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38929. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38930. return false;
  38931. }
  38932. defines._normals = defines._needNormals;
  38933. defines._uvs = defines._needUVs;
  38934. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38935. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38936. defines["TANGENT"] = true;
  38937. }
  38938. if (defines._needUVs) {
  38939. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38940. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38941. }
  38942. else {
  38943. defines["UV1"] = false;
  38944. defines["UV2"] = false;
  38945. }
  38946. if (useVertexColor) {
  38947. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38948. defines["VERTEXCOLOR"] = hasVertexColors;
  38949. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38950. }
  38951. if (useBones) {
  38952. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38953. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38954. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38955. }
  38956. else {
  38957. defines["NUM_BONE_INFLUENCERS"] = 0;
  38958. defines["BonesPerMesh"] = 0;
  38959. }
  38960. }
  38961. if (useMorphTargets) {
  38962. var manager = mesh.morphTargetManager;
  38963. if (manager) {
  38964. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38965. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38966. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38967. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38968. }
  38969. else {
  38970. defines["MORPHTARGETS_TANGENT"] = false;
  38971. defines["MORPHTARGETS_NORMAL"] = false;
  38972. defines["MORPHTARGETS"] = false;
  38973. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38974. }
  38975. }
  38976. return true;
  38977. };
  38978. /**
  38979. * Prepares the defines related to the light information passed in parameter
  38980. * @param scene The scene we are intending to draw
  38981. * @param mesh The mesh the effect is compiling for
  38982. * @param defines The defines to update
  38983. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38984. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38985. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38986. * @returns true if normals will be required for the rest of the effect
  38987. */
  38988. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38989. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38990. if (disableLighting === void 0) { disableLighting = false; }
  38991. if (!defines._areLightsDirty) {
  38992. return defines._needNormals;
  38993. }
  38994. var lightIndex = 0;
  38995. var needNormals = false;
  38996. var needRebuild = false;
  38997. var lightmapMode = false;
  38998. var shadowEnabled = false;
  38999. var specularEnabled = false;
  39000. if (scene.lightsEnabled && !disableLighting) {
  39001. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  39002. var light = _a[_i];
  39003. needNormals = true;
  39004. if (defines["LIGHT" + lightIndex] === undefined) {
  39005. needRebuild = true;
  39006. }
  39007. defines["LIGHT" + lightIndex] = true;
  39008. defines["SPOTLIGHT" + lightIndex] = false;
  39009. defines["HEMILIGHT" + lightIndex] = false;
  39010. defines["POINTLIGHT" + lightIndex] = false;
  39011. defines["DIRLIGHT" + lightIndex] = false;
  39012. var type;
  39013. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39014. type = "SPOTLIGHT" + lightIndex;
  39015. var spotLight = light;
  39016. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39017. }
  39018. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39019. type = "HEMILIGHT" + lightIndex;
  39020. }
  39021. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39022. type = "POINTLIGHT" + lightIndex;
  39023. }
  39024. else {
  39025. type = "DIRLIGHT" + lightIndex;
  39026. }
  39027. defines[type] = true;
  39028. // Specular
  39029. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39030. specularEnabled = true;
  39031. }
  39032. // Shadows
  39033. defines["SHADOW" + lightIndex] = false;
  39034. defines["SHADOWPCF" + lightIndex] = false;
  39035. defines["SHADOWPCSS" + lightIndex] = false;
  39036. defines["SHADOWPOISSON" + lightIndex] = false;
  39037. defines["SHADOWESM" + lightIndex] = false;
  39038. defines["SHADOWCUBE" + lightIndex] = false;
  39039. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39040. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39041. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39042. var shadowGenerator = light.getShadowGenerator();
  39043. if (shadowGenerator) {
  39044. shadowEnabled = true;
  39045. shadowGenerator.prepareDefines(defines, lightIndex);
  39046. }
  39047. }
  39048. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39049. lightmapMode = true;
  39050. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39051. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39052. }
  39053. else {
  39054. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39055. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39056. }
  39057. lightIndex++;
  39058. if (lightIndex === maxSimultaneousLights)
  39059. break;
  39060. }
  39061. }
  39062. defines["SPECULARTERM"] = specularEnabled;
  39063. defines["SHADOWS"] = shadowEnabled;
  39064. // Resetting all other lights if any
  39065. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39066. if (defines["LIGHT" + index] !== undefined) {
  39067. defines["LIGHT" + index] = false;
  39068. defines["HEMILIGHT" + lightIndex] = false;
  39069. defines["POINTLIGHT" + lightIndex] = false;
  39070. defines["DIRLIGHT" + lightIndex] = false;
  39071. defines["SPOTLIGHT" + lightIndex] = false;
  39072. defines["SHADOW" + lightIndex] = false;
  39073. }
  39074. }
  39075. var caps = scene.getEngine().getCaps();
  39076. if (defines["SHADOWFLOAT"] === undefined) {
  39077. needRebuild = true;
  39078. }
  39079. defines["SHADOWFLOAT"] = shadowEnabled &&
  39080. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39081. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39082. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39083. if (needRebuild) {
  39084. defines.rebuild();
  39085. }
  39086. return needNormals;
  39087. };
  39088. /**
  39089. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39090. * that won t be acctive due to defines being turned off.
  39091. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39092. * @param samplersList The samplers list
  39093. * @param defines The defines helping in the list generation
  39094. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39095. */
  39096. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39097. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39098. var uniformsList;
  39099. var uniformBuffersList = null;
  39100. if (uniformsListOrOptions.uniformsNames) {
  39101. var options = uniformsListOrOptions;
  39102. uniformsList = options.uniformsNames;
  39103. uniformBuffersList = options.uniformBuffersNames;
  39104. samplersList = options.samplers;
  39105. defines = options.defines;
  39106. maxSimultaneousLights = options.maxSimultaneousLights;
  39107. }
  39108. else {
  39109. uniformsList = uniformsListOrOptions;
  39110. if (!samplersList) {
  39111. samplersList = [];
  39112. }
  39113. }
  39114. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39115. if (!defines["LIGHT" + lightIndex]) {
  39116. break;
  39117. }
  39118. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39119. if (uniformBuffersList) {
  39120. uniformBuffersList.push("Light" + lightIndex);
  39121. }
  39122. samplersList.push("shadowSampler" + lightIndex);
  39123. samplersList.push("depthSampler" + lightIndex);
  39124. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39125. samplersList.push("projectionLightSampler" + lightIndex);
  39126. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39127. }
  39128. }
  39129. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39130. uniformsList.push("morphTargetInfluences");
  39131. }
  39132. };
  39133. /**
  39134. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39135. * @param defines The defines to update while falling back
  39136. * @param fallbacks The authorized effect fallbacks
  39137. * @param maxSimultaneousLights The maximum number of lights allowed
  39138. * @param rank the current rank of the Effect
  39139. * @returns The newly affected rank
  39140. */
  39141. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39142. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39143. if (rank === void 0) { rank = 0; }
  39144. var lightFallbackRank = 0;
  39145. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39146. if (!defines["LIGHT" + lightIndex]) {
  39147. break;
  39148. }
  39149. if (lightIndex > 0) {
  39150. lightFallbackRank = rank + lightIndex;
  39151. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39152. }
  39153. if (!defines["SHADOWS"]) {
  39154. if (defines["SHADOW" + lightIndex]) {
  39155. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39156. }
  39157. if (defines["SHADOWPCF" + lightIndex]) {
  39158. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39159. }
  39160. if (defines["SHADOWPCSS" + lightIndex]) {
  39161. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39162. }
  39163. if (defines["SHADOWPOISSON" + lightIndex]) {
  39164. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39165. }
  39166. if (defines["SHADOWESM" + lightIndex]) {
  39167. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39168. }
  39169. }
  39170. }
  39171. return lightFallbackRank++;
  39172. };
  39173. /**
  39174. * Prepares the list of attributes required for morph targets according to the effect defines.
  39175. * @param attribs The current list of supported attribs
  39176. * @param mesh The mesh to prepare the morph targets attributes for
  39177. * @param defines The current Defines of the effect
  39178. */
  39179. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39180. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39181. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39182. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39183. var manager = mesh.morphTargetManager;
  39184. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39185. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39186. for (var index = 0; index < influencers; index++) {
  39187. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39188. if (normal) {
  39189. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39190. }
  39191. if (tangent) {
  39192. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39193. }
  39194. if (attribs.length > maxAttributesCount) {
  39195. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39196. }
  39197. }
  39198. }
  39199. };
  39200. /**
  39201. * Prepares the list of attributes required for bones according to the effect defines.
  39202. * @param attribs The current list of supported attribs
  39203. * @param mesh The mesh to prepare the bones attributes for
  39204. * @param defines The current Defines of the effect
  39205. * @param fallbacks The current efffect fallback strategy
  39206. */
  39207. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39208. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39209. fallbacks.addCPUSkinningFallback(0, mesh);
  39210. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39211. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39212. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39213. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39214. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39215. }
  39216. }
  39217. };
  39218. /**
  39219. * Prepares the list of attributes required for instances according to the effect defines.
  39220. * @param attribs The current list of supported attribs
  39221. * @param defines The current Defines of the effect
  39222. */
  39223. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39224. if (defines["INSTANCES"]) {
  39225. attribs.push("world0");
  39226. attribs.push("world1");
  39227. attribs.push("world2");
  39228. attribs.push("world3");
  39229. }
  39230. };
  39231. /**
  39232. * Binds the light shadow information to the effect for the given mesh.
  39233. * @param light The light containing the generator
  39234. * @param scene The scene the lights belongs to
  39235. * @param mesh The mesh we are binding the information to render
  39236. * @param lightIndex The light index in the effect used to render the mesh
  39237. * @param effect The effect we are binding the data to
  39238. */
  39239. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39240. if (light.shadowEnabled && mesh.receiveShadows) {
  39241. var shadowGenerator = light.getShadowGenerator();
  39242. if (shadowGenerator) {
  39243. shadowGenerator.bindShadowLight(lightIndex, effect);
  39244. }
  39245. }
  39246. };
  39247. /**
  39248. * Binds the light information to the effect.
  39249. * @param light The light containing the generator
  39250. * @param effect The effect we are binding the data to
  39251. * @param lightIndex The light index in the effect used to render
  39252. */
  39253. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39254. light.transferToEffect(effect, lightIndex + "");
  39255. };
  39256. /**
  39257. * Binds the lights information from the scene to the effect for the given mesh.
  39258. * @param scene The scene the lights belongs to
  39259. * @param mesh The mesh we are binding the information to render
  39260. * @param effect The effect we are binding the data to
  39261. * @param defines The generated defines for the effect
  39262. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39263. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39264. */
  39265. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39266. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39267. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39268. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39269. for (var i = 0; i < len; i++) {
  39270. var light = mesh._lightSources[i];
  39271. var iAsString = i.toString();
  39272. var scaledIntensity = light.getScaledIntensity();
  39273. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39274. MaterialHelper.BindLightProperties(light, effect, i);
  39275. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39276. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39277. if (defines["SPECULARTERM"]) {
  39278. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39279. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39280. }
  39281. // Shadows
  39282. if (scene.shadowsEnabled) {
  39283. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39284. }
  39285. light._uniformBuffer.update();
  39286. }
  39287. };
  39288. /**
  39289. * Binds the fog information from the scene to the effect for the given mesh.
  39290. * @param scene The scene the lights belongs to
  39291. * @param mesh The mesh we are binding the information to render
  39292. * @param effect The effect we are binding the data to
  39293. */
  39294. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39295. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39296. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39297. effect.setColor3("vFogColor", scene.fogColor);
  39298. }
  39299. };
  39300. /**
  39301. * Binds the bones information from the mesh to the effect.
  39302. * @param mesh The mesh we are binding the information to render
  39303. * @param effect The effect we are binding the data to
  39304. */
  39305. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39306. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39307. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39308. if (matrices && effect) {
  39309. effect.setMatrices("mBones", matrices);
  39310. }
  39311. }
  39312. };
  39313. /**
  39314. * Binds the morph targets information from the mesh to the effect.
  39315. * @param abstractMesh The mesh we are binding the information to render
  39316. * @param effect The effect we are binding the data to
  39317. */
  39318. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39319. var manager = abstractMesh.morphTargetManager;
  39320. if (!abstractMesh || !manager) {
  39321. return;
  39322. }
  39323. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39324. };
  39325. /**
  39326. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39327. * @param defines The generated defines used in the effect
  39328. * @param effect The effect we are binding the data to
  39329. * @param scene The scene we are willing to render with logarithmic scale for
  39330. */
  39331. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39332. if (defines["LOGARITHMICDEPTH"]) {
  39333. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39334. }
  39335. };
  39336. /**
  39337. * Binds the clip plane information from the scene to the effect.
  39338. * @param scene The scene the clip plane information are extracted from
  39339. * @param effect The effect we are binding the data to
  39340. */
  39341. MaterialHelper.BindClipPlane = function (effect, scene) {
  39342. if (scene.clipPlane) {
  39343. var clipPlane = scene.clipPlane;
  39344. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39345. }
  39346. };
  39347. return MaterialHelper;
  39348. }());
  39349. BABYLON.MaterialHelper = MaterialHelper;
  39350. })(BABYLON || (BABYLON = {}));
  39351. //# sourceMappingURL=babylon.materialHelper.js.map
  39352. "use strict";
  39353. var BABYLON;
  39354. (function (BABYLON) {
  39355. var PushMaterial = /** @class */ (function (_super) {
  39356. __extends(PushMaterial, _super);
  39357. function PushMaterial(name, scene) {
  39358. var _this = _super.call(this, name, scene) || this;
  39359. _this._normalMatrix = new BABYLON.Matrix();
  39360. _this.storeEffectOnSubMeshes = true;
  39361. return _this;
  39362. }
  39363. PushMaterial.prototype.getEffect = function () {
  39364. return this._activeEffect;
  39365. };
  39366. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39367. if (!mesh) {
  39368. return false;
  39369. }
  39370. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39371. return true;
  39372. }
  39373. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39374. };
  39375. /**
  39376. * Binds the given world matrix to the active effect
  39377. *
  39378. * @param world the matrix to bind
  39379. */
  39380. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39381. this._activeEffect.setMatrix("world", world);
  39382. };
  39383. /**
  39384. * Binds the given normal matrix to the active effect
  39385. *
  39386. * @param normalMatrix the matrix to bind
  39387. */
  39388. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39389. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39390. };
  39391. PushMaterial.prototype.bind = function (world, mesh) {
  39392. if (!mesh) {
  39393. return;
  39394. }
  39395. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39396. };
  39397. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39398. if (effect === void 0) { effect = null; }
  39399. _super.prototype._afterBind.call(this, mesh);
  39400. this.getScene()._cachedEffect = effect;
  39401. };
  39402. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39403. if (visibility === void 0) { visibility = 1; }
  39404. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39405. };
  39406. return PushMaterial;
  39407. }(BABYLON.Material));
  39408. BABYLON.PushMaterial = PushMaterial;
  39409. })(BABYLON || (BABYLON = {}));
  39410. //# sourceMappingURL=babylon.pushMaterial.js.map
  39411. "use strict";
  39412. var BABYLON;
  39413. (function (BABYLON) {
  39414. /** @ignore */
  39415. var StandardMaterialDefines = /** @class */ (function (_super) {
  39416. __extends(StandardMaterialDefines, _super);
  39417. function StandardMaterialDefines() {
  39418. var _this = _super.call(this) || this;
  39419. _this.MAINUV1 = false;
  39420. _this.MAINUV2 = false;
  39421. _this.DIFFUSE = false;
  39422. _this.DIFFUSEDIRECTUV = 0;
  39423. _this.AMBIENT = false;
  39424. _this.AMBIENTDIRECTUV = 0;
  39425. _this.OPACITY = false;
  39426. _this.OPACITYDIRECTUV = 0;
  39427. _this.OPACITYRGB = false;
  39428. _this.REFLECTION = false;
  39429. _this.EMISSIVE = false;
  39430. _this.EMISSIVEDIRECTUV = 0;
  39431. _this.SPECULAR = false;
  39432. _this.SPECULARDIRECTUV = 0;
  39433. _this.BUMP = false;
  39434. _this.BUMPDIRECTUV = 0;
  39435. _this.PARALLAX = false;
  39436. _this.PARALLAXOCCLUSION = false;
  39437. _this.SPECULAROVERALPHA = false;
  39438. _this.CLIPPLANE = false;
  39439. _this.ALPHATEST = false;
  39440. _this.DEPTHPREPASS = false;
  39441. _this.ALPHAFROMDIFFUSE = false;
  39442. _this.POINTSIZE = false;
  39443. _this.FOG = false;
  39444. _this.SPECULARTERM = false;
  39445. _this.DIFFUSEFRESNEL = false;
  39446. _this.OPACITYFRESNEL = false;
  39447. _this.REFLECTIONFRESNEL = false;
  39448. _this.REFRACTIONFRESNEL = false;
  39449. _this.EMISSIVEFRESNEL = false;
  39450. _this.FRESNEL = false;
  39451. _this.NORMAL = false;
  39452. _this.UV1 = false;
  39453. _this.UV2 = false;
  39454. _this.VERTEXCOLOR = false;
  39455. _this.VERTEXALPHA = false;
  39456. _this.NUM_BONE_INFLUENCERS = 0;
  39457. _this.BonesPerMesh = 0;
  39458. _this.INSTANCES = false;
  39459. _this.GLOSSINESS = false;
  39460. _this.ROUGHNESS = false;
  39461. _this.EMISSIVEASILLUMINATION = false;
  39462. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39463. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39464. _this.LIGHTMAP = false;
  39465. _this.LIGHTMAPDIRECTUV = 0;
  39466. _this.OBJECTSPACE_NORMALMAP = false;
  39467. _this.USELIGHTMAPASSHADOWMAP = false;
  39468. _this.REFLECTIONMAP_3D = false;
  39469. _this.REFLECTIONMAP_SPHERICAL = false;
  39470. _this.REFLECTIONMAP_PLANAR = false;
  39471. _this.REFLECTIONMAP_CUBIC = false;
  39472. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39473. _this.REFLECTIONMAP_PROJECTION = false;
  39474. _this.REFLECTIONMAP_SKYBOX = false;
  39475. _this.REFLECTIONMAP_EXPLICIT = false;
  39476. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39477. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39478. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39479. _this.INVERTCUBICMAP = false;
  39480. _this.LOGARITHMICDEPTH = false;
  39481. _this.REFRACTION = false;
  39482. _this.REFRACTIONMAP_3D = false;
  39483. _this.REFLECTIONOVERALPHA = false;
  39484. _this.TWOSIDEDLIGHTING = false;
  39485. _this.SHADOWFLOAT = false;
  39486. _this.MORPHTARGETS = false;
  39487. _this.MORPHTARGETS_NORMAL = false;
  39488. _this.MORPHTARGETS_TANGENT = false;
  39489. _this.NUM_MORPH_INFLUENCERS = 0;
  39490. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39491. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39492. _this.IMAGEPROCESSING = false;
  39493. _this.VIGNETTE = false;
  39494. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39495. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39496. _this.TONEMAPPING = false;
  39497. _this.CONTRAST = false;
  39498. _this.COLORCURVES = false;
  39499. _this.COLORGRADING = false;
  39500. _this.COLORGRADING3D = false;
  39501. _this.SAMPLER3DGREENDEPTH = false;
  39502. _this.SAMPLER3DBGRMAP = false;
  39503. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39504. _this.EXPOSURE = false;
  39505. _this.GRAIN = false;
  39506. _this.rebuild();
  39507. return _this;
  39508. }
  39509. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39510. var modes = [
  39511. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39512. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39513. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39514. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39515. ];
  39516. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39517. var mode = modes_1[_i];
  39518. this[mode] = (mode === modeToEnable);
  39519. }
  39520. };
  39521. return StandardMaterialDefines;
  39522. }(BABYLON.MaterialDefines));
  39523. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39524. var StandardMaterial = /** @class */ (function (_super) {
  39525. __extends(StandardMaterial, _super);
  39526. function StandardMaterial(name, scene) {
  39527. var _this = _super.call(this, name, scene) || this;
  39528. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39529. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39530. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39531. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39532. _this.specularPower = 64;
  39533. _this._useAlphaFromDiffuseTexture = false;
  39534. _this._useEmissiveAsIllumination = false;
  39535. _this._linkEmissiveWithDiffuse = false;
  39536. _this._useSpecularOverAlpha = false;
  39537. _this._useReflectionOverAlpha = false;
  39538. _this._disableLighting = false;
  39539. _this._useObjectSpaceNormalMap = false;
  39540. _this._useParallax = false;
  39541. _this._useParallaxOcclusion = false;
  39542. _this.parallaxScaleBias = 0.05;
  39543. _this._roughness = 0;
  39544. _this.indexOfRefraction = 0.98;
  39545. _this.invertRefractionY = true;
  39546. _this._useLightmapAsShadowmap = false;
  39547. _this._useReflectionFresnelFromSpecular = false;
  39548. _this._useGlossinessFromSpecularMapAlpha = false;
  39549. _this._maxSimultaneousLights = 4;
  39550. /**
  39551. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39552. */
  39553. _this._invertNormalMapX = false;
  39554. /**
  39555. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39556. */
  39557. _this._invertNormalMapY = false;
  39558. /**
  39559. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39560. */
  39561. _this._twoSidedLighting = false;
  39562. _this._renderTargets = new BABYLON.SmartArray(16);
  39563. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39564. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39565. // Setup the default processing configuration to the scene.
  39566. _this._attachImageProcessingConfiguration(null);
  39567. _this.getRenderTargetTextures = function () {
  39568. _this._renderTargets.reset();
  39569. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39570. _this._renderTargets.push(_this._reflectionTexture);
  39571. }
  39572. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39573. _this._renderTargets.push(_this._refractionTexture);
  39574. }
  39575. return _this._renderTargets;
  39576. };
  39577. return _this;
  39578. }
  39579. ;
  39580. ;
  39581. ;
  39582. ;
  39583. ;
  39584. ;
  39585. ;
  39586. ;
  39587. ;
  39588. ;
  39589. ;
  39590. ;
  39591. ;
  39592. ;
  39593. ;
  39594. ;
  39595. ;
  39596. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39597. /**
  39598. * Gets the image processing configuration used either in this material.
  39599. */
  39600. get: function () {
  39601. return this._imageProcessingConfiguration;
  39602. },
  39603. /**
  39604. * Sets the Default image processing configuration used either in the this material.
  39605. *
  39606. * If sets to null, the scene one is in use.
  39607. */
  39608. set: function (value) {
  39609. this._attachImageProcessingConfiguration(value);
  39610. // Ensure the effect will be rebuilt.
  39611. this._markAllSubMeshesAsTexturesDirty();
  39612. },
  39613. enumerable: true,
  39614. configurable: true
  39615. });
  39616. /**
  39617. * Attaches a new image processing configuration to the Standard Material.
  39618. * @param configuration
  39619. */
  39620. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39621. var _this = this;
  39622. if (configuration === this._imageProcessingConfiguration) {
  39623. return;
  39624. }
  39625. // Detaches observer.
  39626. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39627. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39628. }
  39629. // Pick the scene configuration if needed.
  39630. if (!configuration) {
  39631. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39632. }
  39633. else {
  39634. this._imageProcessingConfiguration = configuration;
  39635. }
  39636. // Attaches observer.
  39637. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39638. _this._markAllSubMeshesAsImageProcessingDirty();
  39639. });
  39640. };
  39641. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39642. /**
  39643. * Gets wether the color curves effect is enabled.
  39644. */
  39645. get: function () {
  39646. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39647. },
  39648. /**
  39649. * Sets wether the color curves effect is enabled.
  39650. */
  39651. set: function (value) {
  39652. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39653. },
  39654. enumerable: true,
  39655. configurable: true
  39656. });
  39657. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39658. /**
  39659. * Gets wether the color grading effect is enabled.
  39660. */
  39661. get: function () {
  39662. return this.imageProcessingConfiguration.colorGradingEnabled;
  39663. },
  39664. /**
  39665. * Gets wether the color grading effect is enabled.
  39666. */
  39667. set: function (value) {
  39668. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39669. },
  39670. enumerable: true,
  39671. configurable: true
  39672. });
  39673. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39674. /**
  39675. * Gets wether tonemapping is enabled or not.
  39676. */
  39677. get: function () {
  39678. return this._imageProcessingConfiguration.toneMappingEnabled;
  39679. },
  39680. /**
  39681. * Sets wether tonemapping is enabled or not
  39682. */
  39683. set: function (value) {
  39684. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39685. },
  39686. enumerable: true,
  39687. configurable: true
  39688. });
  39689. ;
  39690. ;
  39691. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39692. /**
  39693. * The camera exposure used on this material.
  39694. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39695. * This corresponds to a photographic exposure.
  39696. */
  39697. get: function () {
  39698. return this._imageProcessingConfiguration.exposure;
  39699. },
  39700. /**
  39701. * The camera exposure used on this material.
  39702. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39703. * This corresponds to a photographic exposure.
  39704. */
  39705. set: function (value) {
  39706. this._imageProcessingConfiguration.exposure = value;
  39707. },
  39708. enumerable: true,
  39709. configurable: true
  39710. });
  39711. ;
  39712. ;
  39713. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39714. /**
  39715. * Gets The camera contrast used on this material.
  39716. */
  39717. get: function () {
  39718. return this._imageProcessingConfiguration.contrast;
  39719. },
  39720. /**
  39721. * Sets The camera contrast used on this material.
  39722. */
  39723. set: function (value) {
  39724. this._imageProcessingConfiguration.contrast = value;
  39725. },
  39726. enumerable: true,
  39727. configurable: true
  39728. });
  39729. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39730. /**
  39731. * Gets the Color Grading 2D Lookup Texture.
  39732. */
  39733. get: function () {
  39734. return this._imageProcessingConfiguration.colorGradingTexture;
  39735. },
  39736. /**
  39737. * Sets the Color Grading 2D Lookup Texture.
  39738. */
  39739. set: function (value) {
  39740. this._imageProcessingConfiguration.colorGradingTexture = value;
  39741. },
  39742. enumerable: true,
  39743. configurable: true
  39744. });
  39745. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39746. /**
  39747. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39748. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39749. * 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;
  39750. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39751. */
  39752. get: function () {
  39753. return this._imageProcessingConfiguration.colorCurves;
  39754. },
  39755. /**
  39756. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39757. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39758. * 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;
  39759. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39760. */
  39761. set: function (value) {
  39762. this._imageProcessingConfiguration.colorCurves = value;
  39763. },
  39764. enumerable: true,
  39765. configurable: true
  39766. });
  39767. StandardMaterial.prototype.getClassName = function () {
  39768. return "StandardMaterial";
  39769. };
  39770. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39771. get: function () {
  39772. return this._useLogarithmicDepth;
  39773. },
  39774. set: function (value) {
  39775. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39776. this._markAllSubMeshesAsMiscDirty();
  39777. },
  39778. enumerable: true,
  39779. configurable: true
  39780. });
  39781. StandardMaterial.prototype.needAlphaBlending = function () {
  39782. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39783. };
  39784. StandardMaterial.prototype.needAlphaTesting = function () {
  39785. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39786. };
  39787. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39788. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39789. };
  39790. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39791. return this._diffuseTexture;
  39792. };
  39793. /**
  39794. * Child classes can use it to update shaders
  39795. */
  39796. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39797. if (useInstances === void 0) { useInstances = false; }
  39798. if (subMesh.effect && this.isFrozen) {
  39799. if (this._wasPreviouslyReady && subMesh.effect) {
  39800. return true;
  39801. }
  39802. }
  39803. if (!subMesh._materialDefines) {
  39804. subMesh._materialDefines = new StandardMaterialDefines();
  39805. }
  39806. var scene = this.getScene();
  39807. var defines = subMesh._materialDefines;
  39808. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39809. if (defines._renderId === scene.getRenderId()) {
  39810. return true;
  39811. }
  39812. }
  39813. var engine = scene.getEngine();
  39814. // Lights
  39815. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39816. // Textures
  39817. if (defines._areTexturesDirty) {
  39818. defines._needUVs = false;
  39819. defines.MAINUV1 = false;
  39820. defines.MAINUV2 = false;
  39821. if (scene.texturesEnabled) {
  39822. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39823. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39824. return false;
  39825. }
  39826. else {
  39827. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39828. }
  39829. }
  39830. else {
  39831. defines.DIFFUSE = false;
  39832. }
  39833. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39834. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39835. return false;
  39836. }
  39837. else {
  39838. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39839. }
  39840. }
  39841. else {
  39842. defines.AMBIENT = false;
  39843. }
  39844. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39845. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39846. return false;
  39847. }
  39848. else {
  39849. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39850. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39851. }
  39852. }
  39853. else {
  39854. defines.OPACITY = false;
  39855. }
  39856. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39857. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39858. return false;
  39859. }
  39860. else {
  39861. defines._needNormals = true;
  39862. defines.REFLECTION = true;
  39863. defines.ROUGHNESS = (this._roughness > 0);
  39864. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39865. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39866. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39867. switch (this._reflectionTexture.coordinatesMode) {
  39868. case BABYLON.Texture.CUBIC_MODE:
  39869. case BABYLON.Texture.INVCUBIC_MODE:
  39870. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39871. break;
  39872. case BABYLON.Texture.EXPLICIT_MODE:
  39873. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39874. break;
  39875. case BABYLON.Texture.PLANAR_MODE:
  39876. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39877. break;
  39878. case BABYLON.Texture.PROJECTION_MODE:
  39879. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39880. break;
  39881. case BABYLON.Texture.SKYBOX_MODE:
  39882. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39883. break;
  39884. case BABYLON.Texture.SPHERICAL_MODE:
  39885. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39886. break;
  39887. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39888. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39889. break;
  39890. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39891. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39892. break;
  39893. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39894. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39895. break;
  39896. }
  39897. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39898. }
  39899. }
  39900. else {
  39901. defines.REFLECTION = false;
  39902. }
  39903. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39904. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39905. return false;
  39906. }
  39907. else {
  39908. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39909. }
  39910. }
  39911. else {
  39912. defines.EMISSIVE = false;
  39913. }
  39914. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39915. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39916. return false;
  39917. }
  39918. else {
  39919. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39920. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39921. }
  39922. }
  39923. else {
  39924. defines.LIGHTMAP = false;
  39925. }
  39926. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39927. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39928. return false;
  39929. }
  39930. else {
  39931. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39932. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39933. }
  39934. }
  39935. else {
  39936. defines.SPECULAR = false;
  39937. }
  39938. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39939. // Bump texure can not be not blocking.
  39940. if (!this._bumpTexture.isReady()) {
  39941. return false;
  39942. }
  39943. else {
  39944. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39945. defines.PARALLAX = this._useParallax;
  39946. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39947. }
  39948. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39949. }
  39950. else {
  39951. defines.BUMP = false;
  39952. }
  39953. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39954. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39955. return false;
  39956. }
  39957. else {
  39958. defines._needUVs = true;
  39959. defines.REFRACTION = true;
  39960. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39961. }
  39962. }
  39963. else {
  39964. defines.REFRACTION = false;
  39965. }
  39966. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39967. }
  39968. else {
  39969. defines.DIFFUSE = false;
  39970. defines.AMBIENT = false;
  39971. defines.OPACITY = false;
  39972. defines.REFLECTION = false;
  39973. defines.EMISSIVE = false;
  39974. defines.LIGHTMAP = false;
  39975. defines.BUMP = false;
  39976. defines.REFRACTION = false;
  39977. }
  39978. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39979. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39980. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39981. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39982. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39983. }
  39984. if (defines._areImageProcessingDirty) {
  39985. if (!this._imageProcessingConfiguration.isReady()) {
  39986. return false;
  39987. }
  39988. this._imageProcessingConfiguration.prepareDefines(defines);
  39989. }
  39990. if (defines._areFresnelDirty) {
  39991. if (StandardMaterial.FresnelEnabled) {
  39992. // Fresnel
  39993. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39994. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39995. this._reflectionFresnelParameters) {
  39996. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39997. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39998. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39999. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40000. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40001. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40002. defines._needNormals = true;
  40003. defines.FRESNEL = true;
  40004. }
  40005. }
  40006. else {
  40007. defines.FRESNEL = false;
  40008. }
  40009. }
  40010. // Misc.
  40011. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  40012. // Attribs
  40013. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40014. // Values that need to be evaluated on every frame
  40015. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40016. // Get correct effect
  40017. if (defines.isDirty) {
  40018. defines.markAsProcessed();
  40019. scene.resetCachedMaterial();
  40020. // Fallbacks
  40021. var fallbacks = new BABYLON.EffectFallbacks();
  40022. if (defines.REFLECTION) {
  40023. fallbacks.addFallback(0, "REFLECTION");
  40024. }
  40025. if (defines.SPECULAR) {
  40026. fallbacks.addFallback(0, "SPECULAR");
  40027. }
  40028. if (defines.BUMP) {
  40029. fallbacks.addFallback(0, "BUMP");
  40030. }
  40031. if (defines.PARALLAX) {
  40032. fallbacks.addFallback(1, "PARALLAX");
  40033. }
  40034. if (defines.PARALLAXOCCLUSION) {
  40035. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40036. }
  40037. if (defines.SPECULAROVERALPHA) {
  40038. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40039. }
  40040. if (defines.FOG) {
  40041. fallbacks.addFallback(1, "FOG");
  40042. }
  40043. if (defines.POINTSIZE) {
  40044. fallbacks.addFallback(0, "POINTSIZE");
  40045. }
  40046. if (defines.LOGARITHMICDEPTH) {
  40047. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40048. }
  40049. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40050. if (defines.SPECULARTERM) {
  40051. fallbacks.addFallback(0, "SPECULARTERM");
  40052. }
  40053. if (defines.DIFFUSEFRESNEL) {
  40054. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40055. }
  40056. if (defines.OPACITYFRESNEL) {
  40057. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40058. }
  40059. if (defines.REFLECTIONFRESNEL) {
  40060. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40061. }
  40062. if (defines.EMISSIVEFRESNEL) {
  40063. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40064. }
  40065. if (defines.FRESNEL) {
  40066. fallbacks.addFallback(4, "FRESNEL");
  40067. }
  40068. //Attributes
  40069. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40070. if (defines.NORMAL) {
  40071. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40072. }
  40073. if (defines.UV1) {
  40074. attribs.push(BABYLON.VertexBuffer.UVKind);
  40075. }
  40076. if (defines.UV2) {
  40077. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40078. }
  40079. if (defines.VERTEXCOLOR) {
  40080. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40081. }
  40082. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40083. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40084. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40085. var shaderName = "default";
  40086. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40087. "vFogInfos", "vFogColor", "pointSize",
  40088. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40089. "mBones",
  40090. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40091. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40092. "vReflectionPosition", "vReflectionSize",
  40093. "logarithmicDepthConstant", "vTangentSpaceParams"
  40094. ];
  40095. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40096. var uniformBuffers = ["Material", "Scene"];
  40097. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40098. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40099. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40100. uniformsNames: uniforms,
  40101. uniformBuffersNames: uniformBuffers,
  40102. samplers: samplers,
  40103. defines: defines,
  40104. maxSimultaneousLights: this._maxSimultaneousLights
  40105. });
  40106. if (this.customShaderNameResolve) {
  40107. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40108. }
  40109. var join = defines.toString();
  40110. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40111. attributes: attribs,
  40112. uniformsNames: uniforms,
  40113. uniformBuffersNames: uniformBuffers,
  40114. samplers: samplers,
  40115. defines: join,
  40116. fallbacks: fallbacks,
  40117. onCompiled: this.onCompiled,
  40118. onError: this.onError,
  40119. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40120. }, engine), defines);
  40121. this.buildUniformLayout();
  40122. }
  40123. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40124. return false;
  40125. }
  40126. defines._renderId = scene.getRenderId();
  40127. this._wasPreviouslyReady = true;
  40128. return true;
  40129. };
  40130. StandardMaterial.prototype.buildUniformLayout = function () {
  40131. // Order is important !
  40132. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40133. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40134. this._uniformBuffer.addUniform("opacityParts", 4);
  40135. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40136. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40137. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40138. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40139. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40140. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40141. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40142. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40143. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40144. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40145. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40146. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40147. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40148. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40149. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40150. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40151. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40152. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40153. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40154. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40155. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40156. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40157. this._uniformBuffer.addUniform("specularMatrix", 16);
  40158. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40159. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40160. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40161. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40162. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40163. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40164. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40165. this._uniformBuffer.addUniform("pointSize", 1);
  40166. this._uniformBuffer.create();
  40167. };
  40168. StandardMaterial.prototype.unbind = function () {
  40169. if (this._activeEffect) {
  40170. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40171. this._activeEffect.setTexture("reflection2DSampler", null);
  40172. }
  40173. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40174. this._activeEffect.setTexture("refraction2DSampler", null);
  40175. }
  40176. }
  40177. _super.prototype.unbind.call(this);
  40178. };
  40179. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40180. var scene = this.getScene();
  40181. var defines = subMesh._materialDefines;
  40182. if (!defines) {
  40183. return;
  40184. }
  40185. var effect = subMesh.effect;
  40186. if (!effect) {
  40187. return;
  40188. }
  40189. this._activeEffect = effect;
  40190. // Matrices
  40191. this.bindOnlyWorldMatrix(world);
  40192. // Normal Matrix
  40193. if (defines.OBJECTSPACE_NORMALMAP) {
  40194. world.toNormalMatrix(this._normalMatrix);
  40195. this.bindOnlyNormalMatrix(this._normalMatrix);
  40196. }
  40197. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40198. // Bones
  40199. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40200. if (mustRebind) {
  40201. this._uniformBuffer.bindToEffect(effect, "Material");
  40202. this.bindViewProjection(effect);
  40203. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40204. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40205. // Fresnel
  40206. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40207. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40208. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40209. }
  40210. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40211. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40212. }
  40213. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40214. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40215. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40216. }
  40217. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40218. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40219. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40220. }
  40221. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40222. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40223. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40224. }
  40225. }
  40226. // Textures
  40227. if (scene.texturesEnabled) {
  40228. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40229. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40230. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40231. }
  40232. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40233. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40234. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40235. }
  40236. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40237. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40238. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40239. }
  40240. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40241. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40242. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40243. if (this._reflectionTexture.boundingBoxSize) {
  40244. var cubeTexture = this._reflectionTexture;
  40245. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40246. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40247. }
  40248. }
  40249. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40250. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40251. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40252. }
  40253. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40254. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40255. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40256. }
  40257. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40258. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40259. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40260. }
  40261. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40262. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40263. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40264. if (scene._mirroredCameraPosition) {
  40265. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40266. }
  40267. else {
  40268. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40269. }
  40270. }
  40271. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40272. var depth = 1.0;
  40273. if (!this._refractionTexture.isCube) {
  40274. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40275. if (this._refractionTexture.depth) {
  40276. depth = this._refractionTexture.depth;
  40277. }
  40278. }
  40279. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40280. }
  40281. }
  40282. // Point size
  40283. if (this.pointsCloud) {
  40284. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40285. }
  40286. if (defines.SPECULARTERM) {
  40287. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40288. }
  40289. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40290. // Diffuse
  40291. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40292. }
  40293. // Textures
  40294. if (scene.texturesEnabled) {
  40295. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40296. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40297. }
  40298. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40299. effect.setTexture("ambientSampler", this._ambientTexture);
  40300. }
  40301. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40302. effect.setTexture("opacitySampler", this._opacityTexture);
  40303. }
  40304. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40305. if (this._reflectionTexture.isCube) {
  40306. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40307. }
  40308. else {
  40309. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40310. }
  40311. }
  40312. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40313. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40314. }
  40315. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40316. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40317. }
  40318. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40319. effect.setTexture("specularSampler", this._specularTexture);
  40320. }
  40321. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40322. effect.setTexture("bumpSampler", this._bumpTexture);
  40323. }
  40324. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40325. var depth = 1.0;
  40326. if (this._refractionTexture.isCube) {
  40327. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40328. }
  40329. else {
  40330. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40331. }
  40332. }
  40333. }
  40334. // Clip plane
  40335. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40336. // Colors
  40337. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40338. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40339. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40340. }
  40341. if (mustRebind || !this.isFrozen) {
  40342. // Lights
  40343. if (scene.lightsEnabled && !this._disableLighting) {
  40344. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40345. }
  40346. // View
  40347. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40348. this.bindView(effect);
  40349. }
  40350. // Fog
  40351. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40352. // Morph targets
  40353. if (defines.NUM_MORPH_INFLUENCERS) {
  40354. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40355. }
  40356. // Log. depth
  40357. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40358. // image processing
  40359. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40360. this._imageProcessingConfiguration.bind(this._activeEffect);
  40361. }
  40362. }
  40363. this._uniformBuffer.update();
  40364. this._afterBind(mesh, this._activeEffect);
  40365. };
  40366. StandardMaterial.prototype.getAnimatables = function () {
  40367. var results = [];
  40368. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40369. results.push(this._diffuseTexture);
  40370. }
  40371. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40372. results.push(this._ambientTexture);
  40373. }
  40374. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40375. results.push(this._opacityTexture);
  40376. }
  40377. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40378. results.push(this._reflectionTexture);
  40379. }
  40380. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40381. results.push(this._emissiveTexture);
  40382. }
  40383. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40384. results.push(this._specularTexture);
  40385. }
  40386. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40387. results.push(this._bumpTexture);
  40388. }
  40389. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40390. results.push(this._lightmapTexture);
  40391. }
  40392. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40393. results.push(this._refractionTexture);
  40394. }
  40395. return results;
  40396. };
  40397. StandardMaterial.prototype.getActiveTextures = function () {
  40398. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40399. if (this._diffuseTexture) {
  40400. activeTextures.push(this._diffuseTexture);
  40401. }
  40402. if (this._ambientTexture) {
  40403. activeTextures.push(this._ambientTexture);
  40404. }
  40405. if (this._opacityTexture) {
  40406. activeTextures.push(this._opacityTexture);
  40407. }
  40408. if (this._reflectionTexture) {
  40409. activeTextures.push(this._reflectionTexture);
  40410. }
  40411. if (this._emissiveTexture) {
  40412. activeTextures.push(this._emissiveTexture);
  40413. }
  40414. if (this._specularTexture) {
  40415. activeTextures.push(this._specularTexture);
  40416. }
  40417. if (this._bumpTexture) {
  40418. activeTextures.push(this._bumpTexture);
  40419. }
  40420. if (this._lightmapTexture) {
  40421. activeTextures.push(this._lightmapTexture);
  40422. }
  40423. if (this._refractionTexture) {
  40424. activeTextures.push(this._refractionTexture);
  40425. }
  40426. return activeTextures;
  40427. };
  40428. StandardMaterial.prototype.hasTexture = function (texture) {
  40429. if (_super.prototype.hasTexture.call(this, texture)) {
  40430. return true;
  40431. }
  40432. if (this._diffuseTexture === texture) {
  40433. return true;
  40434. }
  40435. if (this._ambientTexture === texture) {
  40436. return true;
  40437. }
  40438. if (this._opacityTexture === texture) {
  40439. return true;
  40440. }
  40441. if (this._reflectionTexture === texture) {
  40442. return true;
  40443. }
  40444. if (this._emissiveTexture === texture) {
  40445. return true;
  40446. }
  40447. if (this._specularTexture === texture) {
  40448. return true;
  40449. }
  40450. if (this._bumpTexture === texture) {
  40451. return true;
  40452. }
  40453. if (this._lightmapTexture === texture) {
  40454. return true;
  40455. }
  40456. if (this._refractionTexture === texture) {
  40457. return true;
  40458. }
  40459. return false;
  40460. };
  40461. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40462. if (forceDisposeTextures) {
  40463. if (this._diffuseTexture) {
  40464. this._diffuseTexture.dispose();
  40465. }
  40466. if (this._ambientTexture) {
  40467. this._ambientTexture.dispose();
  40468. }
  40469. if (this._opacityTexture) {
  40470. this._opacityTexture.dispose();
  40471. }
  40472. if (this._reflectionTexture) {
  40473. this._reflectionTexture.dispose();
  40474. }
  40475. if (this._emissiveTexture) {
  40476. this._emissiveTexture.dispose();
  40477. }
  40478. if (this._specularTexture) {
  40479. this._specularTexture.dispose();
  40480. }
  40481. if (this._bumpTexture) {
  40482. this._bumpTexture.dispose();
  40483. }
  40484. if (this._lightmapTexture) {
  40485. this._lightmapTexture.dispose();
  40486. }
  40487. if (this._refractionTexture) {
  40488. this._refractionTexture.dispose();
  40489. }
  40490. }
  40491. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40492. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40493. }
  40494. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40495. };
  40496. StandardMaterial.prototype.clone = function (name) {
  40497. var _this = this;
  40498. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40499. result.name = name;
  40500. result.id = name;
  40501. return result;
  40502. };
  40503. StandardMaterial.prototype.serialize = function () {
  40504. return BABYLON.SerializationHelper.Serialize(this);
  40505. };
  40506. // Statics
  40507. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40508. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40509. };
  40510. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40511. get: function () {
  40512. return StandardMaterial._DiffuseTextureEnabled;
  40513. },
  40514. set: function (value) {
  40515. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40516. return;
  40517. }
  40518. StandardMaterial._DiffuseTextureEnabled = value;
  40519. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40520. },
  40521. enumerable: true,
  40522. configurable: true
  40523. });
  40524. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40525. get: function () {
  40526. return StandardMaterial._AmbientTextureEnabled;
  40527. },
  40528. set: function (value) {
  40529. if (StandardMaterial._AmbientTextureEnabled === value) {
  40530. return;
  40531. }
  40532. StandardMaterial._AmbientTextureEnabled = value;
  40533. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40534. },
  40535. enumerable: true,
  40536. configurable: true
  40537. });
  40538. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40539. get: function () {
  40540. return StandardMaterial._OpacityTextureEnabled;
  40541. },
  40542. set: function (value) {
  40543. if (StandardMaterial._OpacityTextureEnabled === value) {
  40544. return;
  40545. }
  40546. StandardMaterial._OpacityTextureEnabled = value;
  40547. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40548. },
  40549. enumerable: true,
  40550. configurable: true
  40551. });
  40552. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40553. get: function () {
  40554. return StandardMaterial._ReflectionTextureEnabled;
  40555. },
  40556. set: function (value) {
  40557. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40558. return;
  40559. }
  40560. StandardMaterial._ReflectionTextureEnabled = value;
  40561. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40562. },
  40563. enumerable: true,
  40564. configurable: true
  40565. });
  40566. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40567. get: function () {
  40568. return StandardMaterial._EmissiveTextureEnabled;
  40569. },
  40570. set: function (value) {
  40571. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40572. return;
  40573. }
  40574. StandardMaterial._EmissiveTextureEnabled = value;
  40575. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40576. },
  40577. enumerable: true,
  40578. configurable: true
  40579. });
  40580. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40581. get: function () {
  40582. return StandardMaterial._SpecularTextureEnabled;
  40583. },
  40584. set: function (value) {
  40585. if (StandardMaterial._SpecularTextureEnabled === value) {
  40586. return;
  40587. }
  40588. StandardMaterial._SpecularTextureEnabled = value;
  40589. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40590. },
  40591. enumerable: true,
  40592. configurable: true
  40593. });
  40594. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40595. get: function () {
  40596. return StandardMaterial._BumpTextureEnabled;
  40597. },
  40598. set: function (value) {
  40599. if (StandardMaterial._BumpTextureEnabled === value) {
  40600. return;
  40601. }
  40602. StandardMaterial._BumpTextureEnabled = value;
  40603. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40604. },
  40605. enumerable: true,
  40606. configurable: true
  40607. });
  40608. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40609. get: function () {
  40610. return StandardMaterial._LightmapTextureEnabled;
  40611. },
  40612. set: function (value) {
  40613. if (StandardMaterial._LightmapTextureEnabled === value) {
  40614. return;
  40615. }
  40616. StandardMaterial._LightmapTextureEnabled = value;
  40617. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40618. },
  40619. enumerable: true,
  40620. configurable: true
  40621. });
  40622. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40623. get: function () {
  40624. return StandardMaterial._RefractionTextureEnabled;
  40625. },
  40626. set: function (value) {
  40627. if (StandardMaterial._RefractionTextureEnabled === value) {
  40628. return;
  40629. }
  40630. StandardMaterial._RefractionTextureEnabled = value;
  40631. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40632. },
  40633. enumerable: true,
  40634. configurable: true
  40635. });
  40636. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40637. get: function () {
  40638. return StandardMaterial._ColorGradingTextureEnabled;
  40639. },
  40640. set: function (value) {
  40641. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40642. return;
  40643. }
  40644. StandardMaterial._ColorGradingTextureEnabled = value;
  40645. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40646. },
  40647. enumerable: true,
  40648. configurable: true
  40649. });
  40650. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40651. get: function () {
  40652. return StandardMaterial._FresnelEnabled;
  40653. },
  40654. set: function (value) {
  40655. if (StandardMaterial._FresnelEnabled === value) {
  40656. return;
  40657. }
  40658. StandardMaterial._FresnelEnabled = value;
  40659. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40660. },
  40661. enumerable: true,
  40662. configurable: true
  40663. });
  40664. // Flags used to enable or disable a type of texture for all Standard Materials
  40665. StandardMaterial._DiffuseTextureEnabled = true;
  40666. StandardMaterial._AmbientTextureEnabled = true;
  40667. StandardMaterial._OpacityTextureEnabled = true;
  40668. StandardMaterial._ReflectionTextureEnabled = true;
  40669. StandardMaterial._EmissiveTextureEnabled = true;
  40670. StandardMaterial._SpecularTextureEnabled = true;
  40671. StandardMaterial._BumpTextureEnabled = true;
  40672. StandardMaterial._LightmapTextureEnabled = true;
  40673. StandardMaterial._RefractionTextureEnabled = true;
  40674. StandardMaterial._ColorGradingTextureEnabled = true;
  40675. StandardMaterial._FresnelEnabled = true;
  40676. __decorate([
  40677. BABYLON.serializeAsTexture("diffuseTexture")
  40678. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40679. __decorate([
  40680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40681. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40682. __decorate([
  40683. BABYLON.serializeAsTexture("ambientTexture")
  40684. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40685. __decorate([
  40686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40687. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40688. __decorate([
  40689. BABYLON.serializeAsTexture("opacityTexture")
  40690. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40691. __decorate([
  40692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40693. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40694. __decorate([
  40695. BABYLON.serializeAsTexture("reflectionTexture")
  40696. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40697. __decorate([
  40698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40699. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40700. __decorate([
  40701. BABYLON.serializeAsTexture("emissiveTexture")
  40702. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40703. __decorate([
  40704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40705. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40706. __decorate([
  40707. BABYLON.serializeAsTexture("specularTexture")
  40708. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40709. __decorate([
  40710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40711. ], StandardMaterial.prototype, "specularTexture", void 0);
  40712. __decorate([
  40713. BABYLON.serializeAsTexture("bumpTexture")
  40714. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40715. __decorate([
  40716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40717. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40718. __decorate([
  40719. BABYLON.serializeAsTexture("lightmapTexture")
  40720. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40721. __decorate([
  40722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40723. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40724. __decorate([
  40725. BABYLON.serializeAsTexture("refractionTexture")
  40726. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40727. __decorate([
  40728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40729. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40730. __decorate([
  40731. BABYLON.serializeAsColor3("ambient")
  40732. ], StandardMaterial.prototype, "ambientColor", void 0);
  40733. __decorate([
  40734. BABYLON.serializeAsColor3("diffuse")
  40735. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40736. __decorate([
  40737. BABYLON.serializeAsColor3("specular")
  40738. ], StandardMaterial.prototype, "specularColor", void 0);
  40739. __decorate([
  40740. BABYLON.serializeAsColor3("emissive")
  40741. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40742. __decorate([
  40743. BABYLON.serialize()
  40744. ], StandardMaterial.prototype, "specularPower", void 0);
  40745. __decorate([
  40746. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40747. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40748. __decorate([
  40749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40750. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40751. __decorate([
  40752. BABYLON.serialize("useEmissiveAsIllumination")
  40753. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40754. __decorate([
  40755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40756. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40757. __decorate([
  40758. BABYLON.serialize("linkEmissiveWithDiffuse")
  40759. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40760. __decorate([
  40761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40762. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40763. __decorate([
  40764. BABYLON.serialize("useSpecularOverAlpha")
  40765. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40766. __decorate([
  40767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40768. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40769. __decorate([
  40770. BABYLON.serialize("useReflectionOverAlpha")
  40771. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40772. __decorate([
  40773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40774. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40775. __decorate([
  40776. BABYLON.serialize("disableLighting")
  40777. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40778. __decorate([
  40779. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40780. ], StandardMaterial.prototype, "disableLighting", void 0);
  40781. __decorate([
  40782. BABYLON.serialize("useObjectSpaceNormalMap")
  40783. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40784. __decorate([
  40785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40786. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40787. __decorate([
  40788. BABYLON.serialize("useParallax")
  40789. ], StandardMaterial.prototype, "_useParallax", void 0);
  40790. __decorate([
  40791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40792. ], StandardMaterial.prototype, "useParallax", void 0);
  40793. __decorate([
  40794. BABYLON.serialize("useParallaxOcclusion")
  40795. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40796. __decorate([
  40797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40798. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40799. __decorate([
  40800. BABYLON.serialize()
  40801. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40802. __decorate([
  40803. BABYLON.serialize("roughness")
  40804. ], StandardMaterial.prototype, "_roughness", void 0);
  40805. __decorate([
  40806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40807. ], StandardMaterial.prototype, "roughness", void 0);
  40808. __decorate([
  40809. BABYLON.serialize()
  40810. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40811. __decorate([
  40812. BABYLON.serialize()
  40813. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40814. __decorate([
  40815. BABYLON.serialize("useLightmapAsShadowmap")
  40816. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40817. __decorate([
  40818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40819. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40820. __decorate([
  40821. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40822. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40823. __decorate([
  40824. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40825. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40826. __decorate([
  40827. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40828. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40829. __decorate([
  40830. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40831. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40832. __decorate([
  40833. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40834. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40835. __decorate([
  40836. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40837. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40838. __decorate([
  40839. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40840. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40841. __decorate([
  40842. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40843. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40844. __decorate([
  40845. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40846. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40847. __decorate([
  40848. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40849. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40850. __decorate([
  40851. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40852. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40853. __decorate([
  40854. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40855. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40856. __decorate([
  40857. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40858. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40859. __decorate([
  40860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40861. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40862. __decorate([
  40863. BABYLON.serialize("maxSimultaneousLights")
  40864. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40865. __decorate([
  40866. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40867. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40868. __decorate([
  40869. BABYLON.serialize("invertNormalMapX")
  40870. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40871. __decorate([
  40872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40873. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40874. __decorate([
  40875. BABYLON.serialize("invertNormalMapY")
  40876. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40877. __decorate([
  40878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40879. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40880. __decorate([
  40881. BABYLON.serialize("twoSidedLighting")
  40882. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40883. __decorate([
  40884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40885. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40886. __decorate([
  40887. BABYLON.serialize()
  40888. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40889. return StandardMaterial;
  40890. }(BABYLON.PushMaterial));
  40891. BABYLON.StandardMaterial = StandardMaterial;
  40892. })(BABYLON || (BABYLON = {}));
  40893. //# sourceMappingURL=babylon.standardMaterial.js.map
  40894. "use strict";
  40895. var BABYLON;
  40896. (function (BABYLON) {
  40897. /**
  40898. * Manages the defines for the PBR Material.
  40899. */
  40900. var PBRMaterialDefines = /** @class */ (function (_super) {
  40901. __extends(PBRMaterialDefines, _super);
  40902. /**
  40903. * Initializes the PBR Material defines.
  40904. */
  40905. function PBRMaterialDefines() {
  40906. var _this = _super.call(this) || this;
  40907. _this.PBR = true;
  40908. _this.MAINUV1 = false;
  40909. _this.MAINUV2 = false;
  40910. _this.UV1 = false;
  40911. _this.UV2 = false;
  40912. _this.ALBEDO = false;
  40913. _this.ALBEDODIRECTUV = 0;
  40914. _this.VERTEXCOLOR = false;
  40915. _this.AMBIENT = false;
  40916. _this.AMBIENTDIRECTUV = 0;
  40917. _this.AMBIENTINGRAYSCALE = false;
  40918. _this.OPACITY = false;
  40919. _this.VERTEXALPHA = false;
  40920. _this.OPACITYDIRECTUV = 0;
  40921. _this.OPACITYRGB = false;
  40922. _this.ALPHATEST = false;
  40923. _this.DEPTHPREPASS = false;
  40924. _this.ALPHABLEND = false;
  40925. _this.ALPHAFROMALBEDO = false;
  40926. _this.ALPHATESTVALUE = "0.5";
  40927. _this.SPECULAROVERALPHA = false;
  40928. _this.RADIANCEOVERALPHA = false;
  40929. _this.ALPHAFRESNEL = false;
  40930. _this.LINEARALPHAFRESNEL = false;
  40931. _this.PREMULTIPLYALPHA = false;
  40932. _this.EMISSIVE = false;
  40933. _this.EMISSIVEDIRECTUV = 0;
  40934. _this.REFLECTIVITY = false;
  40935. _this.REFLECTIVITYDIRECTUV = 0;
  40936. _this.SPECULARTERM = false;
  40937. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40938. _this.MICROSURFACEAUTOMATIC = false;
  40939. _this.LODBASEDMICROSFURACE = false;
  40940. _this.MICROSURFACEMAP = false;
  40941. _this.MICROSURFACEMAPDIRECTUV = 0;
  40942. _this.METALLICWORKFLOW = false;
  40943. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40944. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40945. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40946. _this.AOSTOREINMETALMAPRED = false;
  40947. _this.ENVIRONMENTBRDF = false;
  40948. _this.NORMAL = false;
  40949. _this.TANGENT = false;
  40950. _this.BUMP = false;
  40951. _this.BUMPDIRECTUV = 0;
  40952. _this.OBJECTSPACE_NORMALMAP = false;
  40953. _this.PARALLAX = false;
  40954. _this.PARALLAXOCCLUSION = false;
  40955. _this.NORMALXYSCALE = true;
  40956. _this.LIGHTMAP = false;
  40957. _this.LIGHTMAPDIRECTUV = 0;
  40958. _this.USELIGHTMAPASSHADOWMAP = false;
  40959. _this.GAMMALIGHTMAP = false;
  40960. _this.REFLECTION = false;
  40961. _this.REFLECTIONMAP_3D = false;
  40962. _this.REFLECTIONMAP_SPHERICAL = false;
  40963. _this.REFLECTIONMAP_PLANAR = false;
  40964. _this.REFLECTIONMAP_CUBIC = false;
  40965. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40966. _this.REFLECTIONMAP_PROJECTION = false;
  40967. _this.REFLECTIONMAP_SKYBOX = false;
  40968. _this.REFLECTIONMAP_EXPLICIT = false;
  40969. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40970. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40971. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40972. _this.INVERTCUBICMAP = false;
  40973. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40974. _this.USESPHERICALINVERTEX = false;
  40975. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40976. _this.LODINREFLECTIONALPHA = false;
  40977. _this.GAMMAREFLECTION = false;
  40978. _this.RADIANCEOCCLUSION = false;
  40979. _this.HORIZONOCCLUSION = false;
  40980. _this.REFRACTION = false;
  40981. _this.REFRACTIONMAP_3D = false;
  40982. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40983. _this.LODINREFRACTIONALPHA = false;
  40984. _this.GAMMAREFRACTION = false;
  40985. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40986. _this.INSTANCES = false;
  40987. _this.NUM_BONE_INFLUENCERS = 0;
  40988. _this.BonesPerMesh = 0;
  40989. _this.NONUNIFORMSCALING = false;
  40990. _this.MORPHTARGETS = false;
  40991. _this.MORPHTARGETS_NORMAL = false;
  40992. _this.MORPHTARGETS_TANGENT = false;
  40993. _this.NUM_MORPH_INFLUENCERS = 0;
  40994. _this.IMAGEPROCESSING = false;
  40995. _this.VIGNETTE = false;
  40996. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40997. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40998. _this.TONEMAPPING = false;
  40999. _this.CONTRAST = false;
  41000. _this.COLORCURVES = false;
  41001. _this.COLORGRADING = false;
  41002. _this.COLORGRADING3D = false;
  41003. _this.SAMPLER3DGREENDEPTH = false;
  41004. _this.SAMPLER3DBGRMAP = false;
  41005. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41006. _this.EXPOSURE = false;
  41007. _this.GRAIN = false;
  41008. _this.USEPHYSICALLIGHTFALLOFF = false;
  41009. _this.TWOSIDEDLIGHTING = false;
  41010. _this.SHADOWFLOAT = false;
  41011. _this.CLIPPLANE = false;
  41012. _this.POINTSIZE = false;
  41013. _this.FOG = false;
  41014. _this.LOGARITHMICDEPTH = false;
  41015. _this.FORCENORMALFORWARD = false;
  41016. _this.UNLIT = false;
  41017. _this.rebuild();
  41018. return _this;
  41019. }
  41020. /**
  41021. * Resets the PBR Material defines.
  41022. */
  41023. PBRMaterialDefines.prototype.reset = function () {
  41024. _super.prototype.reset.call(this);
  41025. this.ALPHATESTVALUE = "0.5";
  41026. this.PBR = true;
  41027. };
  41028. return PBRMaterialDefines;
  41029. }(BABYLON.MaterialDefines));
  41030. /**
  41031. * The Physically based material base class of BJS.
  41032. *
  41033. * This offers the main features of a standard PBR material.
  41034. * For more information, please refer to the documentation :
  41035. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41036. */
  41037. var PBRBaseMaterial = /** @class */ (function (_super) {
  41038. __extends(PBRBaseMaterial, _super);
  41039. /**
  41040. * Instantiates a new PBRMaterial instance.
  41041. *
  41042. * @param name The material name
  41043. * @param scene The scene the material will be use in.
  41044. */
  41045. function PBRBaseMaterial(name, scene) {
  41046. var _this = _super.call(this, name, scene) || this;
  41047. /**
  41048. * Intensity of the direct lights e.g. the four lights available in your scene.
  41049. * This impacts both the direct diffuse and specular highlights.
  41050. */
  41051. _this._directIntensity = 1.0;
  41052. /**
  41053. * Intensity of the emissive part of the material.
  41054. * This helps controlling the emissive effect without modifying the emissive color.
  41055. */
  41056. _this._emissiveIntensity = 1.0;
  41057. /**
  41058. * Intensity of the environment e.g. how much the environment will light the object
  41059. * either through harmonics for rough material or through the refelction for shiny ones.
  41060. */
  41061. _this._environmentIntensity = 1.0;
  41062. /**
  41063. * This is a special control allowing the reduction of the specular highlights coming from the
  41064. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41065. */
  41066. _this._specularIntensity = 1.0;
  41067. /**
  41068. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41069. */
  41070. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41071. /**
  41072. * Debug Control allowing disabling the bump map on this material.
  41073. */
  41074. _this._disableBumpMap = false;
  41075. /**
  41076. * AKA Occlusion Texture Intensity in other nomenclature.
  41077. */
  41078. _this._ambientTextureStrength = 1.0;
  41079. /**
  41080. * The color of a material in ambient lighting.
  41081. */
  41082. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41083. /**
  41084. * AKA Diffuse Color in other nomenclature.
  41085. */
  41086. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41087. /**
  41088. * AKA Specular Color in other nomenclature.
  41089. */
  41090. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41091. /**
  41092. * The color applied when light is reflected from a material.
  41093. */
  41094. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41095. /**
  41096. * The color applied when light is emitted from a material.
  41097. */
  41098. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41099. /**
  41100. * AKA Glossiness in other nomenclature.
  41101. */
  41102. _this._microSurface = 0.9;
  41103. /**
  41104. * source material index of refraction (IOR)' / 'destination material IOR.
  41105. */
  41106. _this._indexOfRefraction = 0.66;
  41107. /**
  41108. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41109. */
  41110. _this._invertRefractionY = false;
  41111. /**
  41112. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41113. * Materials half opaque for instance using refraction could benefit from this control.
  41114. */
  41115. _this._linkRefractionWithTransparency = false;
  41116. /**
  41117. * Specifies that the material will use the light map as a show map.
  41118. */
  41119. _this._useLightmapAsShadowmap = false;
  41120. /**
  41121. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41122. * makes the reflect vector face the model (under horizon).
  41123. */
  41124. _this._useHorizonOcclusion = true;
  41125. /**
  41126. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41127. * too much the area relying on ambient texture to define their ambient occlusion.
  41128. */
  41129. _this._useRadianceOcclusion = true;
  41130. /**
  41131. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41132. */
  41133. _this._useAlphaFromAlbedoTexture = false;
  41134. /**
  41135. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41136. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41137. */
  41138. _this._useSpecularOverAlpha = true;
  41139. /**
  41140. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41141. */
  41142. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41143. /**
  41144. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41145. */
  41146. _this._useRoughnessFromMetallicTextureAlpha = true;
  41147. /**
  41148. * Specifies if the metallic texture contains the roughness information in its green channel.
  41149. */
  41150. _this._useRoughnessFromMetallicTextureGreen = false;
  41151. /**
  41152. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41153. */
  41154. _this._useMetallnessFromMetallicTextureBlue = false;
  41155. /**
  41156. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41157. */
  41158. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41159. /**
  41160. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41161. */
  41162. _this._useAmbientInGrayScale = false;
  41163. /**
  41164. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41165. * The material will try to infer what glossiness each pixel should be.
  41166. */
  41167. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41168. /**
  41169. * BJS is using an harcoded light falloff based on a manually sets up range.
  41170. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41171. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41172. */
  41173. _this._usePhysicalLightFalloff = true;
  41174. /**
  41175. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41176. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41177. */
  41178. _this._useRadianceOverAlpha = true;
  41179. /**
  41180. * Allows using an object space normal map (instead of tangent space).
  41181. */
  41182. _this._useObjectSpaceNormalMap = false;
  41183. /**
  41184. * Allows using the bump map in parallax mode.
  41185. */
  41186. _this._useParallax = false;
  41187. /**
  41188. * Allows using the bump map in parallax occlusion mode.
  41189. */
  41190. _this._useParallaxOcclusion = false;
  41191. /**
  41192. * Controls the scale bias of the parallax mode.
  41193. */
  41194. _this._parallaxScaleBias = 0.05;
  41195. /**
  41196. * If sets to true, disables all the lights affecting the material.
  41197. */
  41198. _this._disableLighting = false;
  41199. /**
  41200. * Number of Simultaneous lights allowed on the material.
  41201. */
  41202. _this._maxSimultaneousLights = 4;
  41203. /**
  41204. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41205. */
  41206. _this._invertNormalMapX = false;
  41207. /**
  41208. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41209. */
  41210. _this._invertNormalMapY = false;
  41211. /**
  41212. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41213. */
  41214. _this._twoSidedLighting = false;
  41215. /**
  41216. * Defines the alpha limits in alpha test mode.
  41217. */
  41218. _this._alphaCutOff = 0.4;
  41219. /**
  41220. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41221. */
  41222. _this._forceAlphaTest = false;
  41223. /**
  41224. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41225. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41226. */
  41227. _this._useAlphaFresnel = false;
  41228. /**
  41229. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41230. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41231. */
  41232. _this._useLinearAlphaFresnel = false;
  41233. /**
  41234. * The transparency mode of the material.
  41235. */
  41236. _this._transparencyMode = null;
  41237. /**
  41238. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41239. * from cos thetav and roughness:
  41240. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41241. */
  41242. _this._environmentBRDFTexture = null;
  41243. /**
  41244. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41245. */
  41246. _this._forceIrradianceInFragment = false;
  41247. /**
  41248. * Force normal to face away from face.
  41249. */
  41250. _this._forceNormalForward = false;
  41251. /**
  41252. * Stores the available render targets.
  41253. */
  41254. _this._renderTargets = new BABYLON.SmartArray(16);
  41255. /**
  41256. * Sets the global ambient color for the material used in lighting calculations.
  41257. */
  41258. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41259. /**
  41260. * If set to true, no lighting calculations will be applied.
  41261. */
  41262. _this._unlit = false;
  41263. // Setup the default processing configuration to the scene.
  41264. _this._attachImageProcessingConfiguration(null);
  41265. _this.getRenderTargetTextures = function () {
  41266. _this._renderTargets.reset();
  41267. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41268. _this._renderTargets.push(_this._reflectionTexture);
  41269. }
  41270. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41271. _this._renderTargets.push(_this._refractionTexture);
  41272. }
  41273. return _this._renderTargets;
  41274. };
  41275. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41276. return _this;
  41277. }
  41278. /**
  41279. * Attaches a new image processing configuration to the PBR Material.
  41280. * @param configuration
  41281. */
  41282. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41283. var _this = this;
  41284. if (configuration === this._imageProcessingConfiguration) {
  41285. return;
  41286. }
  41287. // Detaches observer.
  41288. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41289. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41290. }
  41291. // Pick the scene configuration if needed.
  41292. if (!configuration) {
  41293. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41294. }
  41295. else {
  41296. this._imageProcessingConfiguration = configuration;
  41297. }
  41298. // Attaches observer.
  41299. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41300. _this._markAllSubMeshesAsImageProcessingDirty();
  41301. });
  41302. };
  41303. /**
  41304. * Gets the name of the material class.
  41305. */
  41306. PBRBaseMaterial.prototype.getClassName = function () {
  41307. return "PBRBaseMaterial";
  41308. };
  41309. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41310. /**
  41311. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41312. */
  41313. get: function () {
  41314. return this._useLogarithmicDepth;
  41315. },
  41316. /**
  41317. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41318. */
  41319. set: function (value) {
  41320. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41321. },
  41322. enumerable: true,
  41323. configurable: true
  41324. });
  41325. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41326. /**
  41327. * Gets the current transparency mode.
  41328. */
  41329. get: function () {
  41330. return this._transparencyMode;
  41331. },
  41332. /**
  41333. * Sets the transparency mode of the material.
  41334. */
  41335. set: function (value) {
  41336. if (this._transparencyMode === value) {
  41337. return;
  41338. }
  41339. this._transparencyMode = value;
  41340. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41341. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41342. },
  41343. enumerable: true,
  41344. configurable: true
  41345. });
  41346. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41347. /**
  41348. * Returns true if alpha blending should be disabled.
  41349. */
  41350. get: function () {
  41351. return (this._linkRefractionWithTransparency ||
  41352. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41353. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41354. },
  41355. enumerable: true,
  41356. configurable: true
  41357. });
  41358. /**
  41359. * Specifies whether or not this material should be rendered in alpha blend mode.
  41360. */
  41361. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41362. if (this._disableAlphaBlending) {
  41363. return false;
  41364. }
  41365. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41366. };
  41367. /**
  41368. * Specifies if the mesh will require alpha blending.
  41369. * @param mesh - BJS mesh.
  41370. */
  41371. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41372. if (this._disableAlphaBlending) {
  41373. return false;
  41374. }
  41375. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41376. };
  41377. /**
  41378. * Specifies whether or not this material should be rendered in alpha test mode.
  41379. */
  41380. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41381. if (this._forceAlphaTest) {
  41382. return true;
  41383. }
  41384. if (this._linkRefractionWithTransparency) {
  41385. return false;
  41386. }
  41387. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41388. };
  41389. /**
  41390. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41391. */
  41392. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41393. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41394. };
  41395. /**
  41396. * Gets the texture used for the alpha test.
  41397. */
  41398. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41399. return this._albedoTexture;
  41400. };
  41401. /**
  41402. * Specifies that the submesh is ready to be used.
  41403. * @param mesh - BJS mesh.
  41404. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41405. * @param useInstances - Specifies that instances should be used.
  41406. * @returns - boolean indicating that the submesh is ready or not.
  41407. */
  41408. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41409. if (subMesh.effect && this.isFrozen) {
  41410. if (this._wasPreviouslyReady) {
  41411. return true;
  41412. }
  41413. }
  41414. if (!subMesh._materialDefines) {
  41415. subMesh._materialDefines = new PBRMaterialDefines();
  41416. }
  41417. var defines = subMesh._materialDefines;
  41418. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41419. if (defines._renderId === this.getScene().getRenderId()) {
  41420. return true;
  41421. }
  41422. }
  41423. var scene = this.getScene();
  41424. var engine = scene.getEngine();
  41425. if (defines._areTexturesDirty) {
  41426. if (scene.texturesEnabled) {
  41427. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41428. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41429. return false;
  41430. }
  41431. }
  41432. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41433. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41434. return false;
  41435. }
  41436. }
  41437. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41438. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41439. return false;
  41440. }
  41441. }
  41442. var reflectionTexture = this._getReflectionTexture();
  41443. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41444. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41445. return false;
  41446. }
  41447. }
  41448. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41449. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41450. return false;
  41451. }
  41452. }
  41453. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41454. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41455. return false;
  41456. }
  41457. }
  41458. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41459. if (this._metallicTexture) {
  41460. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41461. return false;
  41462. }
  41463. }
  41464. else if (this._reflectivityTexture) {
  41465. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41466. return false;
  41467. }
  41468. }
  41469. if (this._microSurfaceTexture) {
  41470. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41471. return false;
  41472. }
  41473. }
  41474. }
  41475. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41476. // Bump texture cannot be not blocking.
  41477. if (!this._bumpTexture.isReady()) {
  41478. return false;
  41479. }
  41480. }
  41481. var refractionTexture = this._getRefractionTexture();
  41482. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41483. if (!refractionTexture.isReadyOrNotBlocking()) {
  41484. return false;
  41485. }
  41486. }
  41487. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41488. // This is blocking.
  41489. if (!this._environmentBRDFTexture.isReady()) {
  41490. return false;
  41491. }
  41492. }
  41493. }
  41494. }
  41495. if (defines._areImageProcessingDirty) {
  41496. if (!this._imageProcessingConfiguration.isReady()) {
  41497. return false;
  41498. }
  41499. }
  41500. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41501. mesh.createNormals(true);
  41502. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41503. }
  41504. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41505. if (effect) {
  41506. scene.resetCachedMaterial();
  41507. subMesh.setEffect(effect, defines);
  41508. this.buildUniformLayout();
  41509. }
  41510. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41511. return false;
  41512. }
  41513. defines._renderId = scene.getRenderId();
  41514. this._wasPreviouslyReady = true;
  41515. return true;
  41516. };
  41517. /**
  41518. * Specifies if the material uses metallic roughness workflow.
  41519. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41520. */
  41521. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41522. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41523. return true;
  41524. }
  41525. return false;
  41526. };
  41527. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41528. if (onCompiled === void 0) { onCompiled = null; }
  41529. if (onError === void 0) { onError = null; }
  41530. if (useInstances === void 0) { useInstances = null; }
  41531. if (useClipPlane === void 0) { useClipPlane = null; }
  41532. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41533. if (!defines.isDirty) {
  41534. return null;
  41535. }
  41536. defines.markAsProcessed();
  41537. var scene = this.getScene();
  41538. var engine = scene.getEngine();
  41539. // Fallbacks
  41540. var fallbacks = new BABYLON.EffectFallbacks();
  41541. var fallbackRank = 0;
  41542. if (defines.USESPHERICALINVERTEX) {
  41543. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41544. }
  41545. if (defines.FOG) {
  41546. fallbacks.addFallback(fallbackRank, "FOG");
  41547. }
  41548. if (defines.POINTSIZE) {
  41549. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41550. }
  41551. if (defines.LOGARITHMICDEPTH) {
  41552. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41553. }
  41554. if (defines.PARALLAX) {
  41555. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41556. }
  41557. if (defines.PARALLAXOCCLUSION) {
  41558. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41559. }
  41560. if (defines.ENVIRONMENTBRDF) {
  41561. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41562. }
  41563. if (defines.TANGENT) {
  41564. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41565. }
  41566. if (defines.BUMP) {
  41567. fallbacks.addFallback(fallbackRank++, "BUMP");
  41568. }
  41569. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41570. if (defines.SPECULARTERM) {
  41571. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41572. }
  41573. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41574. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41575. }
  41576. if (defines.LIGHTMAP) {
  41577. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41578. }
  41579. if (defines.NORMAL) {
  41580. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41581. }
  41582. if (defines.AMBIENT) {
  41583. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41584. }
  41585. if (defines.EMISSIVE) {
  41586. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41587. }
  41588. if (defines.VERTEXCOLOR) {
  41589. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41590. }
  41591. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41592. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41593. }
  41594. if (defines.MORPHTARGETS) {
  41595. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41596. }
  41597. //Attributes
  41598. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41599. if (defines.NORMAL) {
  41600. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41601. }
  41602. if (defines.TANGENT) {
  41603. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41604. }
  41605. if (defines.UV1) {
  41606. attribs.push(BABYLON.VertexBuffer.UVKind);
  41607. }
  41608. if (defines.UV2) {
  41609. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41610. }
  41611. if (defines.VERTEXCOLOR) {
  41612. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41613. }
  41614. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41615. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41616. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41617. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41618. "vFogInfos", "vFogColor", "pointSize",
  41619. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41620. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41621. "mBones",
  41622. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41623. "vLightingIntensity",
  41624. "logarithmicDepthConstant",
  41625. "vSphericalX", "vSphericalY", "vSphericalZ",
  41626. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41627. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41628. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41629. "vTangentSpaceParams"
  41630. ];
  41631. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41632. "bumpSampler", "lightmapSampler", "opacitySampler",
  41633. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41634. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41635. "microSurfaceSampler", "environmentBrdfSampler"];
  41636. var uniformBuffers = ["Material", "Scene"];
  41637. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41638. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41639. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41640. uniformsNames: uniforms,
  41641. uniformBuffersNames: uniformBuffers,
  41642. samplers: samplers,
  41643. defines: defines,
  41644. maxSimultaneousLights: this._maxSimultaneousLights
  41645. });
  41646. var join = defines.toString();
  41647. return engine.createEffect("pbr", {
  41648. attributes: attribs,
  41649. uniformsNames: uniforms,
  41650. uniformBuffersNames: uniformBuffers,
  41651. samplers: samplers,
  41652. defines: join,
  41653. fallbacks: fallbacks,
  41654. onCompiled: onCompiled,
  41655. onError: onError,
  41656. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41657. }, engine);
  41658. };
  41659. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41660. if (useInstances === void 0) { useInstances = null; }
  41661. if (useClipPlane === void 0) { useClipPlane = null; }
  41662. var scene = this.getScene();
  41663. var engine = scene.getEngine();
  41664. // Lights
  41665. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41666. defines._needNormals = true;
  41667. // Textures
  41668. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41669. if (defines._areTexturesDirty) {
  41670. defines._needUVs = false;
  41671. if (scene.texturesEnabled) {
  41672. if (scene.getEngine().getCaps().textureLOD) {
  41673. defines.LODBASEDMICROSFURACE = true;
  41674. }
  41675. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41676. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41677. }
  41678. else {
  41679. defines.ALBEDO = false;
  41680. }
  41681. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41682. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41683. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41684. }
  41685. else {
  41686. defines.AMBIENT = false;
  41687. }
  41688. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41689. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41690. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41691. }
  41692. else {
  41693. defines.OPACITY = false;
  41694. }
  41695. var reflectionTexture = this._getReflectionTexture();
  41696. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41697. defines.REFLECTION = true;
  41698. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41699. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41700. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41701. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41702. defines.INVERTCUBICMAP = true;
  41703. }
  41704. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41705. switch (reflectionTexture.coordinatesMode) {
  41706. case BABYLON.Texture.CUBIC_MODE:
  41707. case BABYLON.Texture.INVCUBIC_MODE:
  41708. defines.REFLECTIONMAP_CUBIC = true;
  41709. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41710. break;
  41711. case BABYLON.Texture.EXPLICIT_MODE:
  41712. defines.REFLECTIONMAP_EXPLICIT = true;
  41713. break;
  41714. case BABYLON.Texture.PLANAR_MODE:
  41715. defines.REFLECTIONMAP_PLANAR = true;
  41716. break;
  41717. case BABYLON.Texture.PROJECTION_MODE:
  41718. defines.REFLECTIONMAP_PROJECTION = true;
  41719. break;
  41720. case BABYLON.Texture.SKYBOX_MODE:
  41721. defines.REFLECTIONMAP_SKYBOX = true;
  41722. break;
  41723. case BABYLON.Texture.SPHERICAL_MODE:
  41724. defines.REFLECTIONMAP_SPHERICAL = true;
  41725. break;
  41726. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41727. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41728. break;
  41729. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41730. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41731. break;
  41732. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41733. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41734. break;
  41735. }
  41736. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41737. if (reflectionTexture.sphericalPolynomial) {
  41738. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41739. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41740. defines.USESPHERICALINVERTEX = false;
  41741. }
  41742. else {
  41743. defines.USESPHERICALINVERTEX = true;
  41744. }
  41745. }
  41746. }
  41747. }
  41748. else {
  41749. defines.REFLECTION = false;
  41750. defines.REFLECTIONMAP_3D = false;
  41751. defines.REFLECTIONMAP_SPHERICAL = false;
  41752. defines.REFLECTIONMAP_PLANAR = false;
  41753. defines.REFLECTIONMAP_CUBIC = false;
  41754. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41755. defines.REFLECTIONMAP_PROJECTION = false;
  41756. defines.REFLECTIONMAP_SKYBOX = false;
  41757. defines.REFLECTIONMAP_EXPLICIT = false;
  41758. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41759. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41760. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41761. defines.INVERTCUBICMAP = false;
  41762. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41763. defines.USESPHERICALINVERTEX = false;
  41764. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41765. defines.LODINREFLECTIONALPHA = false;
  41766. defines.GAMMAREFLECTION = false;
  41767. }
  41768. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41769. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41770. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41771. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41772. }
  41773. else {
  41774. defines.LIGHTMAP = false;
  41775. }
  41776. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41777. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41778. }
  41779. else {
  41780. defines.EMISSIVE = false;
  41781. }
  41782. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41783. if (this._metallicTexture) {
  41784. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41785. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41786. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41787. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41788. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41789. }
  41790. else if (this._reflectivityTexture) {
  41791. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41792. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41793. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41794. }
  41795. else {
  41796. defines.REFLECTIVITY = false;
  41797. }
  41798. if (this._microSurfaceTexture) {
  41799. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41800. }
  41801. else {
  41802. defines.MICROSURFACEMAP = false;
  41803. }
  41804. }
  41805. else {
  41806. defines.REFLECTIVITY = false;
  41807. defines.MICROSURFACEMAP = false;
  41808. }
  41809. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41810. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41811. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41812. defines.PARALLAX = true;
  41813. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41814. }
  41815. else {
  41816. defines.PARALLAX = false;
  41817. }
  41818. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41819. }
  41820. else {
  41821. defines.BUMP = false;
  41822. }
  41823. var refractionTexture = this._getRefractionTexture();
  41824. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41825. defines.REFRACTION = true;
  41826. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41827. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41828. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41829. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41830. if (this._linkRefractionWithTransparency) {
  41831. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41832. }
  41833. }
  41834. else {
  41835. defines.REFRACTION = false;
  41836. }
  41837. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41838. defines.ENVIRONMENTBRDF = true;
  41839. }
  41840. else {
  41841. defines.ENVIRONMENTBRDF = false;
  41842. }
  41843. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41844. defines.ALPHAFROMALBEDO = true;
  41845. }
  41846. else {
  41847. defines.ALPHAFROMALBEDO = false;
  41848. }
  41849. }
  41850. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41851. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41852. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41853. if (!this.backFaceCulling && this._twoSidedLighting) {
  41854. defines.TWOSIDEDLIGHTING = true;
  41855. }
  41856. else {
  41857. defines.TWOSIDEDLIGHTING = false;
  41858. }
  41859. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41860. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41861. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41862. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41863. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41864. }
  41865. if (defines._areImageProcessingDirty) {
  41866. this._imageProcessingConfiguration.prepareDefines(defines);
  41867. }
  41868. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41869. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41870. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41871. // Misc.
  41872. if (defines._areMiscDirty) {
  41873. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41874. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41875. }
  41876. // Values that need to be evaluated on every frame
  41877. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41878. // Attribs
  41879. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41880. };
  41881. /**
  41882. * Force shader compilation
  41883. */
  41884. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41885. var _this = this;
  41886. var localOptions = __assign({ clipPlane: false }, options);
  41887. var defines = new PBRMaterialDefines();
  41888. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41889. if (effect.isReady()) {
  41890. if (onCompiled) {
  41891. onCompiled(this);
  41892. }
  41893. }
  41894. else {
  41895. effect.onCompileObservable.add(function () {
  41896. if (onCompiled) {
  41897. onCompiled(_this);
  41898. }
  41899. });
  41900. }
  41901. };
  41902. /**
  41903. * Initializes the uniform buffer layout for the shader.
  41904. */
  41905. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41906. // Order is important !
  41907. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41908. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41909. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41910. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41911. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41912. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41913. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41914. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41915. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41916. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41917. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41918. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41919. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41920. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41921. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41922. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41923. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41924. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41925. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41926. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41927. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41928. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41929. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41930. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41931. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41932. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41933. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41934. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41935. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41936. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41937. this._uniformBuffer.addUniform("pointSize", 1);
  41938. this._uniformBuffer.create();
  41939. };
  41940. /**
  41941. * Unbinds the textures.
  41942. */
  41943. PBRBaseMaterial.prototype.unbind = function () {
  41944. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41945. this._uniformBuffer.setTexture("reflectionSampler", null);
  41946. }
  41947. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41948. this._uniformBuffer.setTexture("refractionSampler", null);
  41949. }
  41950. _super.prototype.unbind.call(this);
  41951. };
  41952. /**
  41953. * Binds the submesh data.
  41954. * @param world - The world matrix.
  41955. * @param mesh - The BJS mesh.
  41956. * @param subMesh - A submesh of the BJS mesh.
  41957. */
  41958. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41959. var scene = this.getScene();
  41960. var defines = subMesh._materialDefines;
  41961. if (!defines) {
  41962. return;
  41963. }
  41964. var effect = subMesh.effect;
  41965. if (!effect) {
  41966. return;
  41967. }
  41968. this._activeEffect = effect;
  41969. // Matrices
  41970. this.bindOnlyWorldMatrix(world);
  41971. // Normal Matrix
  41972. if (defines.OBJECTSPACE_NORMALMAP) {
  41973. world.toNormalMatrix(this._normalMatrix);
  41974. this.bindOnlyNormalMatrix(this._normalMatrix);
  41975. }
  41976. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41977. // Bones
  41978. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41979. var reflectionTexture = null;
  41980. if (mustRebind) {
  41981. this._uniformBuffer.bindToEffect(effect, "Material");
  41982. this.bindViewProjection(effect);
  41983. reflectionTexture = this._getReflectionTexture();
  41984. var refractionTexture = this._getRefractionTexture();
  41985. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41986. // Texture uniforms
  41987. if (scene.texturesEnabled) {
  41988. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41989. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41990. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41991. }
  41992. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41993. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41994. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41995. }
  41996. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41997. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41998. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41999. }
  42000. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42001. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  42002. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  42003. if (reflectionTexture.boundingBoxSize) {
  42004. var cubeTexture = reflectionTexture;
  42005. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42006. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42007. }
  42008. var polynomials = reflectionTexture.sphericalPolynomial;
  42009. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  42010. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  42011. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  42012. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42013. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42014. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42015. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42016. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42017. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42018. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42019. }
  42020. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42021. }
  42022. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42023. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42024. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42025. }
  42026. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42027. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42028. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42029. }
  42030. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42031. if (this._metallicTexture) {
  42032. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42033. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42034. }
  42035. else if (this._reflectivityTexture) {
  42036. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42037. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42038. }
  42039. if (this._microSurfaceTexture) {
  42040. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42041. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42042. }
  42043. }
  42044. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42045. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42046. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42047. if (scene._mirroredCameraPosition) {
  42048. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42049. }
  42050. else {
  42051. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42052. }
  42053. }
  42054. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42055. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42056. var depth = 1.0;
  42057. if (!refractionTexture.isCube) {
  42058. if (refractionTexture.depth) {
  42059. depth = refractionTexture.depth;
  42060. }
  42061. }
  42062. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42063. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42064. }
  42065. }
  42066. // Point size
  42067. if (this.pointsCloud) {
  42068. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42069. }
  42070. // Colors
  42071. if (defines.METALLICWORKFLOW) {
  42072. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42073. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42074. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42075. }
  42076. else {
  42077. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42078. }
  42079. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42080. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42081. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42082. // Misc
  42083. this._lightingInfos.x = this._directIntensity;
  42084. this._lightingInfos.y = this._emissiveIntensity;
  42085. this._lightingInfos.z = this._environmentIntensity;
  42086. this._lightingInfos.w = this._specularIntensity;
  42087. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42088. }
  42089. // Textures
  42090. if (scene.texturesEnabled) {
  42091. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42092. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42093. }
  42094. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42095. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42096. }
  42097. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42098. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42099. }
  42100. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42101. if (defines.LODBASEDMICROSFURACE) {
  42102. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42103. }
  42104. else {
  42105. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42106. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42107. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42108. }
  42109. }
  42110. if (defines.ENVIRONMENTBRDF) {
  42111. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42112. }
  42113. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42114. if (defines.LODBASEDMICROSFURACE) {
  42115. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42116. }
  42117. else {
  42118. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42119. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42120. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42121. }
  42122. }
  42123. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42124. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42125. }
  42126. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42127. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42128. }
  42129. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42130. if (this._metallicTexture) {
  42131. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42132. }
  42133. else if (this._reflectivityTexture) {
  42134. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42135. }
  42136. if (this._microSurfaceTexture) {
  42137. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42138. }
  42139. }
  42140. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42141. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42142. }
  42143. }
  42144. // Clip plane
  42145. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42146. // Colors
  42147. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42148. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42149. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42150. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42151. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42152. }
  42153. if (mustRebind || !this.isFrozen) {
  42154. // Lights
  42155. if (scene.lightsEnabled && !this._disableLighting) {
  42156. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42157. }
  42158. // View
  42159. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42160. this.bindView(effect);
  42161. }
  42162. // Fog
  42163. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42164. // Morph targets
  42165. if (defines.NUM_MORPH_INFLUENCERS) {
  42166. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42167. }
  42168. // image processing
  42169. this._imageProcessingConfiguration.bind(this._activeEffect);
  42170. // Log. depth
  42171. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42172. }
  42173. this._uniformBuffer.update();
  42174. this._afterBind(mesh);
  42175. };
  42176. /**
  42177. * Returns the animatable textures.
  42178. * @returns - Array of animatable textures.
  42179. */
  42180. PBRBaseMaterial.prototype.getAnimatables = function () {
  42181. var results = [];
  42182. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42183. results.push(this._albedoTexture);
  42184. }
  42185. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42186. results.push(this._ambientTexture);
  42187. }
  42188. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42189. results.push(this._opacityTexture);
  42190. }
  42191. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42192. results.push(this._reflectionTexture);
  42193. }
  42194. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42195. results.push(this._emissiveTexture);
  42196. }
  42197. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42198. results.push(this._metallicTexture);
  42199. }
  42200. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42201. results.push(this._reflectivityTexture);
  42202. }
  42203. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42204. results.push(this._bumpTexture);
  42205. }
  42206. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42207. results.push(this._lightmapTexture);
  42208. }
  42209. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42210. results.push(this._refractionTexture);
  42211. }
  42212. return results;
  42213. };
  42214. /**
  42215. * Returns the texture used for reflections.
  42216. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42217. */
  42218. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42219. if (this._reflectionTexture) {
  42220. return this._reflectionTexture;
  42221. }
  42222. return this.getScene().environmentTexture;
  42223. };
  42224. /**
  42225. * Returns the texture used for refraction or null if none is used.
  42226. * @returns - Refection texture if present. If no refraction texture and refraction
  42227. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42228. */
  42229. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42230. if (this._refractionTexture) {
  42231. return this._refractionTexture;
  42232. }
  42233. if (this._linkRefractionWithTransparency) {
  42234. return this.getScene().environmentTexture;
  42235. }
  42236. return null;
  42237. };
  42238. /**
  42239. * Disposes the resources of the material.
  42240. * @param forceDisposeEffect - Forces the disposal of effects.
  42241. * @param forceDisposeTextures - Forces the disposal of all textures.
  42242. */
  42243. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42244. if (forceDisposeTextures) {
  42245. if (this._albedoTexture) {
  42246. this._albedoTexture.dispose();
  42247. }
  42248. if (this._ambientTexture) {
  42249. this._ambientTexture.dispose();
  42250. }
  42251. if (this._opacityTexture) {
  42252. this._opacityTexture.dispose();
  42253. }
  42254. if (this._reflectionTexture) {
  42255. this._reflectionTexture.dispose();
  42256. }
  42257. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42258. this._environmentBRDFTexture.dispose();
  42259. }
  42260. if (this._emissiveTexture) {
  42261. this._emissiveTexture.dispose();
  42262. }
  42263. if (this._metallicTexture) {
  42264. this._metallicTexture.dispose();
  42265. }
  42266. if (this._reflectivityTexture) {
  42267. this._reflectivityTexture.dispose();
  42268. }
  42269. if (this._bumpTexture) {
  42270. this._bumpTexture.dispose();
  42271. }
  42272. if (this._lightmapTexture) {
  42273. this._lightmapTexture.dispose();
  42274. }
  42275. if (this._refractionTexture) {
  42276. this._refractionTexture.dispose();
  42277. }
  42278. }
  42279. this._renderTargets.dispose();
  42280. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42281. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42282. }
  42283. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42284. };
  42285. /**
  42286. * Stores the reflectivity values based on metallic roughness workflow.
  42287. */
  42288. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42289. __decorate([
  42290. BABYLON.serializeAsImageProcessingConfiguration()
  42291. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42292. __decorate([
  42293. BABYLON.serialize()
  42294. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42295. __decorate([
  42296. BABYLON.serialize()
  42297. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42298. return PBRBaseMaterial;
  42299. }(BABYLON.PushMaterial));
  42300. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42301. })(BABYLON || (BABYLON = {}));
  42302. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42303. "use strict";
  42304. var BABYLON;
  42305. (function (BABYLON) {
  42306. /**
  42307. * The Physically based simple base material of BJS.
  42308. *
  42309. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42310. * It is used as the base class for both the specGloss and metalRough conventions.
  42311. */
  42312. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42313. __extends(PBRBaseSimpleMaterial, _super);
  42314. /**
  42315. * Instantiates a new PBRMaterial instance.
  42316. *
  42317. * @param name The material name
  42318. * @param scene The scene the material will be use in.
  42319. */
  42320. function PBRBaseSimpleMaterial(name, scene) {
  42321. var _this = _super.call(this, name, scene) || this;
  42322. /**
  42323. * Number of Simultaneous lights allowed on the material.
  42324. */
  42325. _this.maxSimultaneousLights = 4;
  42326. /**
  42327. * If sets to true, disables all the lights affecting the material.
  42328. */
  42329. _this.disableLighting = false;
  42330. /**
  42331. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42332. */
  42333. _this.invertNormalMapX = false;
  42334. /**
  42335. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42336. */
  42337. _this.invertNormalMapY = false;
  42338. /**
  42339. * Emissivie color used to self-illuminate the model.
  42340. */
  42341. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42342. /**
  42343. * Occlusion Channel Strenght.
  42344. */
  42345. _this.occlusionStrength = 1.0;
  42346. _this.useLightmapAsShadowmap = false;
  42347. _this._useAlphaFromAlbedoTexture = true;
  42348. _this._useAmbientInGrayScale = true;
  42349. return _this;
  42350. }
  42351. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42352. /**
  42353. * Gets the current double sided mode.
  42354. */
  42355. get: function () {
  42356. return this._twoSidedLighting;
  42357. },
  42358. /**
  42359. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42360. */
  42361. set: function (value) {
  42362. if (this._twoSidedLighting === value) {
  42363. return;
  42364. }
  42365. this._twoSidedLighting = value;
  42366. this.backFaceCulling = !value;
  42367. this._markAllSubMeshesAsTexturesDirty();
  42368. },
  42369. enumerable: true,
  42370. configurable: true
  42371. });
  42372. /**
  42373. * Return the active textures of the material.
  42374. */
  42375. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42376. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42377. if (this.environmentTexture) {
  42378. activeTextures.push(this.environmentTexture);
  42379. }
  42380. if (this.normalTexture) {
  42381. activeTextures.push(this.normalTexture);
  42382. }
  42383. if (this.emissiveTexture) {
  42384. activeTextures.push(this.emissiveTexture);
  42385. }
  42386. if (this.occlusionTexture) {
  42387. activeTextures.push(this.occlusionTexture);
  42388. }
  42389. if (this.lightmapTexture) {
  42390. activeTextures.push(this.lightmapTexture);
  42391. }
  42392. return activeTextures;
  42393. };
  42394. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42395. if (_super.prototype.hasTexture.call(this, texture)) {
  42396. return true;
  42397. }
  42398. if (this.lightmapTexture === texture) {
  42399. return true;
  42400. }
  42401. return false;
  42402. };
  42403. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42404. return "PBRBaseSimpleMaterial";
  42405. };
  42406. __decorate([
  42407. BABYLON.serialize(),
  42408. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42409. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42410. __decorate([
  42411. BABYLON.serialize(),
  42412. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42413. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42414. __decorate([
  42415. BABYLON.serializeAsTexture(),
  42416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42417. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42418. __decorate([
  42419. BABYLON.serialize(),
  42420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42421. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42422. __decorate([
  42423. BABYLON.serialize(),
  42424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42425. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42426. __decorate([
  42427. BABYLON.serializeAsTexture(),
  42428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42429. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42430. __decorate([
  42431. BABYLON.serializeAsColor3("emissive"),
  42432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42433. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42434. __decorate([
  42435. BABYLON.serializeAsTexture(),
  42436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42437. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42438. __decorate([
  42439. BABYLON.serialize(),
  42440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42441. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42442. __decorate([
  42443. BABYLON.serializeAsTexture(),
  42444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42445. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42446. __decorate([
  42447. BABYLON.serialize(),
  42448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42449. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42450. __decorate([
  42451. BABYLON.serialize()
  42452. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42453. __decorate([
  42454. BABYLON.serializeAsTexture(),
  42455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42456. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42457. __decorate([
  42458. BABYLON.serialize(),
  42459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42460. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42461. return PBRBaseSimpleMaterial;
  42462. }(BABYLON.PBRBaseMaterial));
  42463. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42464. })(BABYLON || (BABYLON = {}));
  42465. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42466. "use strict";
  42467. var BABYLON;
  42468. (function (BABYLON) {
  42469. /**
  42470. * The Physically based material of BJS.
  42471. *
  42472. * This offers the main features of a standard PBR material.
  42473. * For more information, please refer to the documentation :
  42474. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42475. */
  42476. var PBRMaterial = /** @class */ (function (_super) {
  42477. __extends(PBRMaterial, _super);
  42478. /**
  42479. * Instantiates a new PBRMaterial instance.
  42480. *
  42481. * @param name The material name
  42482. * @param scene The scene the material will be use in.
  42483. */
  42484. function PBRMaterial(name, scene) {
  42485. var _this = _super.call(this, name, scene) || this;
  42486. /**
  42487. * Intensity of the direct lights e.g. the four lights available in your scene.
  42488. * This impacts both the direct diffuse and specular highlights.
  42489. */
  42490. _this.directIntensity = 1.0;
  42491. /**
  42492. * Intensity of the emissive part of the material.
  42493. * This helps controlling the emissive effect without modifying the emissive color.
  42494. */
  42495. _this.emissiveIntensity = 1.0;
  42496. /**
  42497. * Intensity of the environment e.g. how much the environment will light the object
  42498. * either through harmonics for rough material or through the refelction for shiny ones.
  42499. */
  42500. _this.environmentIntensity = 1.0;
  42501. /**
  42502. * This is a special control allowing the reduction of the specular highlights coming from the
  42503. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42504. */
  42505. _this.specularIntensity = 1.0;
  42506. /**
  42507. * Debug Control allowing disabling the bump map on this material.
  42508. */
  42509. _this.disableBumpMap = false;
  42510. /**
  42511. * AKA Occlusion Texture Intensity in other nomenclature.
  42512. */
  42513. _this.ambientTextureStrength = 1.0;
  42514. /**
  42515. * The color of a material in ambient lighting.
  42516. */
  42517. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42518. /**
  42519. * AKA Diffuse Color in other nomenclature.
  42520. */
  42521. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42522. /**
  42523. * AKA Specular Color in other nomenclature.
  42524. */
  42525. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42526. /**
  42527. * The color reflected from the material.
  42528. */
  42529. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42530. /**
  42531. * The color emitted from the material.
  42532. */
  42533. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42534. /**
  42535. * AKA Glossiness in other nomenclature.
  42536. */
  42537. _this.microSurface = 1.0;
  42538. /**
  42539. * source material index of refraction (IOR)' / 'destination material IOR.
  42540. */
  42541. _this.indexOfRefraction = 0.66;
  42542. /**
  42543. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42544. */
  42545. _this.invertRefractionY = false;
  42546. /**
  42547. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42548. * Materials half opaque for instance using refraction could benefit from this control.
  42549. */
  42550. _this.linkRefractionWithTransparency = false;
  42551. _this.useLightmapAsShadowmap = false;
  42552. /**
  42553. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42554. */
  42555. _this.useAlphaFromAlbedoTexture = false;
  42556. /**
  42557. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42558. */
  42559. _this.forceAlphaTest = false;
  42560. /**
  42561. * Defines the alpha limits in alpha test mode.
  42562. */
  42563. _this.alphaCutOff = 0.4;
  42564. /**
  42565. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42566. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42567. */
  42568. _this.useSpecularOverAlpha = true;
  42569. /**
  42570. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42571. */
  42572. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42573. /**
  42574. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42575. */
  42576. _this.useRoughnessFromMetallicTextureAlpha = true;
  42577. /**
  42578. * Specifies if the metallic texture contains the roughness information in its green channel.
  42579. */
  42580. _this.useRoughnessFromMetallicTextureGreen = false;
  42581. /**
  42582. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42583. */
  42584. _this.useMetallnessFromMetallicTextureBlue = false;
  42585. /**
  42586. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42587. */
  42588. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42589. /**
  42590. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42591. */
  42592. _this.useAmbientInGrayScale = false;
  42593. /**
  42594. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42595. * The material will try to infer what glossiness each pixel should be.
  42596. */
  42597. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42598. /**
  42599. * BJS is using an harcoded light falloff based on a manually sets up range.
  42600. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42601. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42602. */
  42603. _this.usePhysicalLightFalloff = true;
  42604. /**
  42605. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42606. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42607. */
  42608. _this.useRadianceOverAlpha = true;
  42609. /**
  42610. * Allows using an object space normal map (instead of tangent space).
  42611. */
  42612. _this.useObjectSpaceNormalMap = false;
  42613. /**
  42614. * Allows using the bump map in parallax mode.
  42615. */
  42616. _this.useParallax = false;
  42617. /**
  42618. * Allows using the bump map in parallax occlusion mode.
  42619. */
  42620. _this.useParallaxOcclusion = false;
  42621. /**
  42622. * Controls the scale bias of the parallax mode.
  42623. */
  42624. _this.parallaxScaleBias = 0.05;
  42625. /**
  42626. * If sets to true, disables all the lights affecting the material.
  42627. */
  42628. _this.disableLighting = false;
  42629. /**
  42630. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42631. */
  42632. _this.forceIrradianceInFragment = false;
  42633. /**
  42634. * Number of Simultaneous lights allowed on the material.
  42635. */
  42636. _this.maxSimultaneousLights = 4;
  42637. /**
  42638. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42639. */
  42640. _this.invertNormalMapX = false;
  42641. /**
  42642. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42643. */
  42644. _this.invertNormalMapY = false;
  42645. /**
  42646. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42647. */
  42648. _this.twoSidedLighting = false;
  42649. /**
  42650. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42651. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42652. */
  42653. _this.useAlphaFresnel = false;
  42654. /**
  42655. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42656. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42657. */
  42658. _this.useLinearAlphaFresnel = false;
  42659. /**
  42660. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42661. * And/Or occlude the blended part.
  42662. */
  42663. _this.environmentBRDFTexture = null;
  42664. /**
  42665. * Force normal to face away from face.
  42666. */
  42667. _this.forceNormalForward = false;
  42668. /**
  42669. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42670. * makes the reflect vector face the model (under horizon).
  42671. */
  42672. _this.useHorizonOcclusion = true;
  42673. /**
  42674. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42675. * too much the area relying on ambient texture to define their ambient occlusion.
  42676. */
  42677. _this.useRadianceOcclusion = true;
  42678. /**
  42679. * If set to true, no lighting calculations will be applied.
  42680. */
  42681. _this.unlit = false;
  42682. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42683. return _this;
  42684. }
  42685. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42686. /**
  42687. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42688. */
  42689. get: function () {
  42690. return this._PBRMATERIAL_OPAQUE;
  42691. },
  42692. enumerable: true,
  42693. configurable: true
  42694. });
  42695. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42696. /**
  42697. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42698. */
  42699. get: function () {
  42700. return this._PBRMATERIAL_ALPHATEST;
  42701. },
  42702. enumerable: true,
  42703. configurable: true
  42704. });
  42705. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42706. /**
  42707. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42708. */
  42709. get: function () {
  42710. return this._PBRMATERIAL_ALPHABLEND;
  42711. },
  42712. enumerable: true,
  42713. configurable: true
  42714. });
  42715. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42716. /**
  42717. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42718. * They are also discarded below the alpha cutoff threshold to improve performances.
  42719. */
  42720. get: function () {
  42721. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42722. },
  42723. enumerable: true,
  42724. configurable: true
  42725. });
  42726. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42727. /**
  42728. * Gets the image processing configuration used either in this material.
  42729. */
  42730. get: function () {
  42731. return this._imageProcessingConfiguration;
  42732. },
  42733. /**
  42734. * Sets the Default image processing configuration used either in the this material.
  42735. *
  42736. * If sets to null, the scene one is in use.
  42737. */
  42738. set: function (value) {
  42739. this._attachImageProcessingConfiguration(value);
  42740. // Ensure the effect will be rebuilt.
  42741. this._markAllSubMeshesAsTexturesDirty();
  42742. },
  42743. enumerable: true,
  42744. configurable: true
  42745. });
  42746. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42747. /**
  42748. * Gets wether the color curves effect is enabled.
  42749. */
  42750. get: function () {
  42751. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42752. },
  42753. /**
  42754. * Sets wether the color curves effect is enabled.
  42755. */
  42756. set: function (value) {
  42757. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42758. },
  42759. enumerable: true,
  42760. configurable: true
  42761. });
  42762. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42763. /**
  42764. * Gets wether the color grading effect is enabled.
  42765. */
  42766. get: function () {
  42767. return this.imageProcessingConfiguration.colorGradingEnabled;
  42768. },
  42769. /**
  42770. * Gets wether the color grading effect is enabled.
  42771. */
  42772. set: function (value) {
  42773. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42774. },
  42775. enumerable: true,
  42776. configurable: true
  42777. });
  42778. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42779. /**
  42780. * Gets wether tonemapping is enabled or not.
  42781. */
  42782. get: function () {
  42783. return this._imageProcessingConfiguration.toneMappingEnabled;
  42784. },
  42785. /**
  42786. * Sets wether tonemapping is enabled or not
  42787. */
  42788. set: function (value) {
  42789. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42790. },
  42791. enumerable: true,
  42792. configurable: true
  42793. });
  42794. ;
  42795. ;
  42796. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42797. /**
  42798. * The camera exposure used on this material.
  42799. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42800. * This corresponds to a photographic exposure.
  42801. */
  42802. get: function () {
  42803. return this._imageProcessingConfiguration.exposure;
  42804. },
  42805. /**
  42806. * The camera exposure used on this material.
  42807. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42808. * This corresponds to a photographic exposure.
  42809. */
  42810. set: function (value) {
  42811. this._imageProcessingConfiguration.exposure = value;
  42812. },
  42813. enumerable: true,
  42814. configurable: true
  42815. });
  42816. ;
  42817. ;
  42818. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42819. /**
  42820. * Gets The camera contrast used on this material.
  42821. */
  42822. get: function () {
  42823. return this._imageProcessingConfiguration.contrast;
  42824. },
  42825. /**
  42826. * Sets The camera contrast used on this material.
  42827. */
  42828. set: function (value) {
  42829. this._imageProcessingConfiguration.contrast = value;
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42835. /**
  42836. * Gets the Color Grading 2D Lookup Texture.
  42837. */
  42838. get: function () {
  42839. return this._imageProcessingConfiguration.colorGradingTexture;
  42840. },
  42841. /**
  42842. * Sets the Color Grading 2D Lookup Texture.
  42843. */
  42844. set: function (value) {
  42845. this._imageProcessingConfiguration.colorGradingTexture = value;
  42846. },
  42847. enumerable: true,
  42848. configurable: true
  42849. });
  42850. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42851. /**
  42852. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42853. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42854. * 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;
  42855. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42856. */
  42857. get: function () {
  42858. return this._imageProcessingConfiguration.colorCurves;
  42859. },
  42860. /**
  42861. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42862. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42863. * 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;
  42864. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42865. */
  42866. set: function (value) {
  42867. this._imageProcessingConfiguration.colorCurves = value;
  42868. },
  42869. enumerable: true,
  42870. configurable: true
  42871. });
  42872. /**
  42873. * Returns the name of this material class.
  42874. */
  42875. PBRMaterial.prototype.getClassName = function () {
  42876. return "PBRMaterial";
  42877. };
  42878. /**
  42879. * Returns an array of the actively used textures.
  42880. * @returns - Array of BaseTextures
  42881. */
  42882. PBRMaterial.prototype.getActiveTextures = function () {
  42883. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42884. if (this._albedoTexture) {
  42885. activeTextures.push(this._albedoTexture);
  42886. }
  42887. if (this._ambientTexture) {
  42888. activeTextures.push(this._ambientTexture);
  42889. }
  42890. if (this._opacityTexture) {
  42891. activeTextures.push(this._opacityTexture);
  42892. }
  42893. if (this._reflectionTexture) {
  42894. activeTextures.push(this._reflectionTexture);
  42895. }
  42896. if (this._emissiveTexture) {
  42897. activeTextures.push(this._emissiveTexture);
  42898. }
  42899. if (this._reflectivityTexture) {
  42900. activeTextures.push(this._reflectivityTexture);
  42901. }
  42902. if (this._metallicTexture) {
  42903. activeTextures.push(this._metallicTexture);
  42904. }
  42905. if (this._microSurfaceTexture) {
  42906. activeTextures.push(this._microSurfaceTexture);
  42907. }
  42908. if (this._bumpTexture) {
  42909. activeTextures.push(this._bumpTexture);
  42910. }
  42911. if (this._lightmapTexture) {
  42912. activeTextures.push(this._lightmapTexture);
  42913. }
  42914. if (this._refractionTexture) {
  42915. activeTextures.push(this._refractionTexture);
  42916. }
  42917. return activeTextures;
  42918. };
  42919. /**
  42920. * Checks to see if a texture is used in the material.
  42921. * @param texture - Base texture to use.
  42922. * @returns - Boolean specifying if a texture is used in the material.
  42923. */
  42924. PBRMaterial.prototype.hasTexture = function (texture) {
  42925. if (_super.prototype.hasTexture.call(this, texture)) {
  42926. return true;
  42927. }
  42928. if (this._albedoTexture === texture) {
  42929. return true;
  42930. }
  42931. if (this._ambientTexture === texture) {
  42932. return true;
  42933. }
  42934. if (this._opacityTexture === texture) {
  42935. return true;
  42936. }
  42937. if (this._reflectionTexture === texture) {
  42938. return true;
  42939. }
  42940. if (this._reflectivityTexture === texture) {
  42941. return true;
  42942. }
  42943. if (this._metallicTexture === texture) {
  42944. return true;
  42945. }
  42946. if (this._microSurfaceTexture === texture) {
  42947. return true;
  42948. }
  42949. if (this._bumpTexture === texture) {
  42950. return true;
  42951. }
  42952. if (this._lightmapTexture === texture) {
  42953. return true;
  42954. }
  42955. if (this._refractionTexture === texture) {
  42956. return true;
  42957. }
  42958. return false;
  42959. };
  42960. /**
  42961. * Makes a duplicate of the current material.
  42962. * @param name - name to use for the new material.
  42963. */
  42964. PBRMaterial.prototype.clone = function (name) {
  42965. var _this = this;
  42966. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42967. clone.id = name;
  42968. clone.name = name;
  42969. return clone;
  42970. };
  42971. /**
  42972. * Serializes this PBR Material.
  42973. * @returns - An object with the serialized material.
  42974. */
  42975. PBRMaterial.prototype.serialize = function () {
  42976. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42977. serializationObject.customType = "BABYLON.PBRMaterial";
  42978. return serializationObject;
  42979. };
  42980. // Statics
  42981. /**
  42982. * Parses a PBR Material from a serialized object.
  42983. * @param source - Serialized object.
  42984. * @param scene - BJS scene instance.
  42985. * @param rootUrl - url for the scene object
  42986. * @returns - PBRMaterial
  42987. */
  42988. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42989. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42990. };
  42991. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42992. /**
  42993. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42994. */
  42995. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42996. /**
  42997. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42998. */
  42999. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  43000. /**
  43001. * 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.
  43002. * They are also discarded below the alpha cutoff threshold to improve performances.
  43003. */
  43004. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  43005. __decorate([
  43006. BABYLON.serialize(),
  43007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43008. ], PBRMaterial.prototype, "directIntensity", void 0);
  43009. __decorate([
  43010. BABYLON.serialize(),
  43011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43012. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43013. __decorate([
  43014. BABYLON.serialize(),
  43015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43016. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43017. __decorate([
  43018. BABYLON.serialize(),
  43019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43020. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43021. __decorate([
  43022. BABYLON.serialize(),
  43023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43024. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43025. __decorate([
  43026. BABYLON.serializeAsTexture(),
  43027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43028. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43029. __decorate([
  43030. BABYLON.serializeAsTexture(),
  43031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43032. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43033. __decorate([
  43034. BABYLON.serialize(),
  43035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43036. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43037. __decorate([
  43038. BABYLON.serializeAsTexture(),
  43039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43040. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43041. __decorate([
  43042. BABYLON.serializeAsTexture(),
  43043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43044. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43045. __decorate([
  43046. BABYLON.serializeAsTexture(),
  43047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43048. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43049. __decorate([
  43050. BABYLON.serializeAsTexture(),
  43051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43052. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43053. __decorate([
  43054. BABYLON.serializeAsTexture(),
  43055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43056. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43057. __decorate([
  43058. BABYLON.serialize(),
  43059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43060. ], PBRMaterial.prototype, "metallic", void 0);
  43061. __decorate([
  43062. BABYLON.serialize(),
  43063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43064. ], PBRMaterial.prototype, "roughness", void 0);
  43065. __decorate([
  43066. BABYLON.serializeAsTexture(),
  43067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43068. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43069. __decorate([
  43070. BABYLON.serializeAsTexture(),
  43071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43072. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43073. __decorate([
  43074. BABYLON.serializeAsTexture(),
  43075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43076. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43077. __decorate([
  43078. BABYLON.serializeAsTexture(),
  43079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43080. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43081. __decorate([
  43082. BABYLON.serializeAsColor3("ambient"),
  43083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43084. ], PBRMaterial.prototype, "ambientColor", void 0);
  43085. __decorate([
  43086. BABYLON.serializeAsColor3("albedo"),
  43087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43088. ], PBRMaterial.prototype, "albedoColor", void 0);
  43089. __decorate([
  43090. BABYLON.serializeAsColor3("reflectivity"),
  43091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43092. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43093. __decorate([
  43094. BABYLON.serializeAsColor3("reflection"),
  43095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43096. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43097. __decorate([
  43098. BABYLON.serializeAsColor3("emissive"),
  43099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43100. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43101. __decorate([
  43102. BABYLON.serialize(),
  43103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43104. ], PBRMaterial.prototype, "microSurface", void 0);
  43105. __decorate([
  43106. BABYLON.serialize(),
  43107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43108. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43109. __decorate([
  43110. BABYLON.serialize(),
  43111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43112. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43113. __decorate([
  43114. BABYLON.serialize(),
  43115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43116. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43117. __decorate([
  43118. BABYLON.serialize(),
  43119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43120. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43121. __decorate([
  43122. BABYLON.serialize(),
  43123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43124. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43125. __decorate([
  43126. BABYLON.serialize(),
  43127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43128. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43129. __decorate([
  43130. BABYLON.serialize(),
  43131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43132. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43133. __decorate([
  43134. BABYLON.serialize(),
  43135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43136. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43137. __decorate([
  43138. BABYLON.serialize(),
  43139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43140. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43141. __decorate([
  43142. BABYLON.serialize(),
  43143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43144. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43145. __decorate([
  43146. BABYLON.serialize(),
  43147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43148. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43149. __decorate([
  43150. BABYLON.serialize(),
  43151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43152. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43153. __decorate([
  43154. BABYLON.serialize(),
  43155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43156. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43157. __decorate([
  43158. BABYLON.serialize(),
  43159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43160. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43161. __decorate([
  43162. BABYLON.serialize(),
  43163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43164. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43165. __decorate([
  43166. BABYLON.serialize(),
  43167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43168. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43169. __decorate([
  43170. BABYLON.serialize(),
  43171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43172. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43173. __decorate([
  43174. BABYLON.serialize(),
  43175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43176. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43177. __decorate([
  43178. BABYLON.serialize(),
  43179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43180. ], PBRMaterial.prototype, "useParallax", void 0);
  43181. __decorate([
  43182. BABYLON.serialize(),
  43183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43184. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43185. __decorate([
  43186. BABYLON.serialize(),
  43187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43188. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43189. __decorate([
  43190. BABYLON.serialize(),
  43191. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43192. ], PBRMaterial.prototype, "disableLighting", void 0);
  43193. __decorate([
  43194. BABYLON.serialize(),
  43195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43196. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43197. __decorate([
  43198. BABYLON.serialize(),
  43199. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43200. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43201. __decorate([
  43202. BABYLON.serialize(),
  43203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43204. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43205. __decorate([
  43206. BABYLON.serialize(),
  43207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43208. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43209. __decorate([
  43210. BABYLON.serialize(),
  43211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43212. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43213. __decorate([
  43214. BABYLON.serialize(),
  43215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43216. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43217. __decorate([
  43218. BABYLON.serialize(),
  43219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43220. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43221. __decorate([
  43222. BABYLON.serializeAsTexture(),
  43223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43224. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43225. __decorate([
  43226. BABYLON.serialize(),
  43227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43228. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43229. __decorate([
  43230. BABYLON.serialize(),
  43231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43232. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43233. __decorate([
  43234. BABYLON.serialize(),
  43235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43236. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43237. __decorate([
  43238. BABYLON.serialize(),
  43239. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43240. ], PBRMaterial.prototype, "unlit", void 0);
  43241. return PBRMaterial;
  43242. }(BABYLON.PBRBaseMaterial));
  43243. BABYLON.PBRMaterial = PBRMaterial;
  43244. })(BABYLON || (BABYLON = {}));
  43245. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43246. "use strict";
  43247. var BABYLON;
  43248. (function (BABYLON) {
  43249. /**
  43250. * The PBR material of BJS following the metal roughness convention.
  43251. *
  43252. * This fits to the PBR convention in the GLTF definition:
  43253. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43254. */
  43255. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43256. __extends(PBRMetallicRoughnessMaterial, _super);
  43257. /**
  43258. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43259. *
  43260. * @param name The material name
  43261. * @param scene The scene the material will be use in.
  43262. */
  43263. function PBRMetallicRoughnessMaterial(name, scene) {
  43264. var _this = _super.call(this, name, scene) || this;
  43265. _this._useRoughnessFromMetallicTextureAlpha = false;
  43266. _this._useRoughnessFromMetallicTextureGreen = true;
  43267. _this._useMetallnessFromMetallicTextureBlue = true;
  43268. _this.metallic = 1.0;
  43269. _this.roughness = 1.0;
  43270. return _this;
  43271. }
  43272. /**
  43273. * Return the currrent class name of the material.
  43274. */
  43275. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43276. return "PBRMetallicRoughnessMaterial";
  43277. };
  43278. /**
  43279. * Return the active textures of the material.
  43280. */
  43281. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43282. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43283. if (this.baseTexture) {
  43284. activeTextures.push(this.baseTexture);
  43285. }
  43286. if (this.metallicRoughnessTexture) {
  43287. activeTextures.push(this.metallicRoughnessTexture);
  43288. }
  43289. return activeTextures;
  43290. };
  43291. /**
  43292. * Checks to see if a texture is used in the material.
  43293. * @param texture - Base texture to use.
  43294. * @returns - Boolean specifying if a texture is used in the material.
  43295. */
  43296. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43297. if (_super.prototype.hasTexture.call(this, texture)) {
  43298. return true;
  43299. }
  43300. if (this.baseTexture === texture) {
  43301. return true;
  43302. }
  43303. if (this.metallicRoughnessTexture === texture) {
  43304. return true;
  43305. }
  43306. return false;
  43307. };
  43308. /**
  43309. * Makes a duplicate of the current material.
  43310. * @param name - name to use for the new material.
  43311. */
  43312. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43313. var _this = this;
  43314. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43315. clone.id = name;
  43316. clone.name = name;
  43317. return clone;
  43318. };
  43319. /**
  43320. * Serialize the material to a parsable JSON object.
  43321. */
  43322. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43323. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43324. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43325. return serializationObject;
  43326. };
  43327. /**
  43328. * Parses a JSON object correponding to the serialize function.
  43329. */
  43330. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43331. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43332. };
  43333. __decorate([
  43334. BABYLON.serializeAsColor3(),
  43335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43336. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43337. __decorate([
  43338. BABYLON.serializeAsTexture(),
  43339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43340. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43341. __decorate([
  43342. BABYLON.serialize(),
  43343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43344. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43345. __decorate([
  43346. BABYLON.serialize(),
  43347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43348. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43349. __decorate([
  43350. BABYLON.serializeAsTexture(),
  43351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43352. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43353. return PBRMetallicRoughnessMaterial;
  43354. }(BABYLON.PBRBaseSimpleMaterial));
  43355. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43356. })(BABYLON || (BABYLON = {}));
  43357. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43358. "use strict";
  43359. var BABYLON;
  43360. (function (BABYLON) {
  43361. /**
  43362. * The PBR material of BJS following the specular glossiness convention.
  43363. *
  43364. * This fits to the PBR convention in the GLTF definition:
  43365. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43366. */
  43367. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43368. __extends(PBRSpecularGlossinessMaterial, _super);
  43369. /**
  43370. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43371. *
  43372. * @param name The material name
  43373. * @param scene The scene the material will be use in.
  43374. */
  43375. function PBRSpecularGlossinessMaterial(name, scene) {
  43376. var _this = _super.call(this, name, scene) || this;
  43377. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43378. return _this;
  43379. }
  43380. /**
  43381. * Return the currrent class name of the material.
  43382. */
  43383. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43384. return "PBRSpecularGlossinessMaterial";
  43385. };
  43386. /**
  43387. * Return the active textures of the material.
  43388. */
  43389. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43390. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43391. if (this.diffuseTexture) {
  43392. activeTextures.push(this.diffuseTexture);
  43393. }
  43394. if (this.specularGlossinessTexture) {
  43395. activeTextures.push(this.specularGlossinessTexture);
  43396. }
  43397. return activeTextures;
  43398. };
  43399. /**
  43400. * Checks to see if a texture is used in the material.
  43401. * @param texture - Base texture to use.
  43402. * @returns - Boolean specifying if a texture is used in the material.
  43403. */
  43404. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43405. if (_super.prototype.hasTexture.call(this, texture)) {
  43406. return true;
  43407. }
  43408. if (this.diffuseTexture === texture) {
  43409. return true;
  43410. }
  43411. if (this.specularGlossinessTexture === texture) {
  43412. return true;
  43413. }
  43414. return false;
  43415. };
  43416. /**
  43417. * Makes a duplicate of the current material.
  43418. * @param name - name to use for the new material.
  43419. */
  43420. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43421. var _this = this;
  43422. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43423. clone.id = name;
  43424. clone.name = name;
  43425. return clone;
  43426. };
  43427. /**
  43428. * Serialize the material to a parsable JSON object.
  43429. */
  43430. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43431. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43432. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43433. return serializationObject;
  43434. };
  43435. /**
  43436. * Parses a JSON object correponding to the serialize function.
  43437. */
  43438. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43439. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43440. };
  43441. __decorate([
  43442. BABYLON.serializeAsColor3("diffuse"),
  43443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43444. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43445. __decorate([
  43446. BABYLON.serializeAsTexture(),
  43447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43448. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43449. __decorate([
  43450. BABYLON.serializeAsColor3("specular"),
  43451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43452. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43453. __decorate([
  43454. BABYLON.serialize(),
  43455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43456. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43457. __decorate([
  43458. BABYLON.serializeAsTexture(),
  43459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43460. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43461. return PBRSpecularGlossinessMaterial;
  43462. }(BABYLON.PBRBaseSimpleMaterial));
  43463. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43464. })(BABYLON || (BABYLON = {}));
  43465. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43466. "use strict";
  43467. var BABYLON;
  43468. (function (BABYLON) {
  43469. BABYLON.CameraInputTypes = {};
  43470. var CameraInputsManager = /** @class */ (function () {
  43471. function CameraInputsManager(camera) {
  43472. this.attached = {};
  43473. this.camera = camera;
  43474. this.checkInputs = function () { };
  43475. }
  43476. /**
  43477. * Add an input method to a camera.
  43478. * builtin inputs example: camera.inputs.addGamepad();
  43479. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43480. * @param input camera input method
  43481. */
  43482. CameraInputsManager.prototype.add = function (input) {
  43483. var type = input.getSimpleName();
  43484. if (this.attached[type]) {
  43485. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43486. return;
  43487. }
  43488. this.attached[type] = input;
  43489. input.camera = this.camera;
  43490. //for checkInputs, we are dynamically creating a function
  43491. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43492. if (input.checkInputs) {
  43493. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43494. }
  43495. if (this.attachedElement) {
  43496. input.attachControl(this.attachedElement);
  43497. }
  43498. };
  43499. /**
  43500. * Remove a specific input method from a camera
  43501. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43502. * @param inputToRemove camera input method
  43503. */
  43504. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43505. for (var cam in this.attached) {
  43506. var input = this.attached[cam];
  43507. if (input === inputToRemove) {
  43508. input.detachControl(this.attachedElement);
  43509. input.camera = null;
  43510. delete this.attached[cam];
  43511. this.rebuildInputCheck();
  43512. }
  43513. }
  43514. };
  43515. CameraInputsManager.prototype.removeByType = function (inputType) {
  43516. for (var cam in this.attached) {
  43517. var input = this.attached[cam];
  43518. if (input.getClassName() === inputType) {
  43519. input.detachControl(this.attachedElement);
  43520. input.camera = null;
  43521. delete this.attached[cam];
  43522. this.rebuildInputCheck();
  43523. }
  43524. }
  43525. };
  43526. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43527. var current = this.checkInputs;
  43528. return function () {
  43529. current();
  43530. fn();
  43531. };
  43532. };
  43533. CameraInputsManager.prototype.attachInput = function (input) {
  43534. if (this.attachedElement) {
  43535. input.attachControl(this.attachedElement, this.noPreventDefault);
  43536. }
  43537. };
  43538. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43539. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43540. if (this.attachedElement) {
  43541. return;
  43542. }
  43543. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43544. this.attachedElement = element;
  43545. this.noPreventDefault = noPreventDefault;
  43546. for (var cam in this.attached) {
  43547. this.attached[cam].attachControl(element, noPreventDefault);
  43548. }
  43549. };
  43550. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43551. if (disconnect === void 0) { disconnect = false; }
  43552. if (this.attachedElement !== element) {
  43553. return;
  43554. }
  43555. for (var cam in this.attached) {
  43556. this.attached[cam].detachControl(element);
  43557. if (disconnect) {
  43558. this.attached[cam].camera = null;
  43559. }
  43560. }
  43561. this.attachedElement = null;
  43562. };
  43563. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43564. this.checkInputs = function () { };
  43565. for (var cam in this.attached) {
  43566. var input = this.attached[cam];
  43567. if (input.checkInputs) {
  43568. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43569. }
  43570. }
  43571. };
  43572. /**
  43573. * Remove all attached input methods from a camera
  43574. */
  43575. CameraInputsManager.prototype.clear = function () {
  43576. if (this.attachedElement) {
  43577. this.detachElement(this.attachedElement, true);
  43578. }
  43579. this.attached = {};
  43580. this.attachedElement = null;
  43581. this.checkInputs = function () { };
  43582. };
  43583. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43584. var inputs = {};
  43585. for (var cam in this.attached) {
  43586. var input = this.attached[cam];
  43587. var res = BABYLON.SerializationHelper.Serialize(input);
  43588. inputs[input.getClassName()] = res;
  43589. }
  43590. serializedCamera.inputsmgr = inputs;
  43591. };
  43592. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43593. var parsedInputs = parsedCamera.inputsmgr;
  43594. if (parsedInputs) {
  43595. this.clear();
  43596. for (var n in parsedInputs) {
  43597. var construct = BABYLON.CameraInputTypes[n];
  43598. if (construct) {
  43599. var parsedinput = parsedInputs[n];
  43600. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43601. this.add(input);
  43602. }
  43603. }
  43604. }
  43605. else {
  43606. //2016-03-08 this part is for managing backward compatibility
  43607. for (var n in this.attached) {
  43608. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43609. if (construct) {
  43610. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43611. this.remove(this.attached[n]);
  43612. this.add(input);
  43613. }
  43614. }
  43615. }
  43616. };
  43617. return CameraInputsManager;
  43618. }());
  43619. BABYLON.CameraInputsManager = CameraInputsManager;
  43620. })(BABYLON || (BABYLON = {}));
  43621. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43622. "use strict";
  43623. var BABYLON;
  43624. (function (BABYLON) {
  43625. var TargetCamera = /** @class */ (function (_super) {
  43626. __extends(TargetCamera, _super);
  43627. function TargetCamera(name, position, scene) {
  43628. var _this = _super.call(this, name, position, scene) || this;
  43629. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43630. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43631. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43632. _this.speed = 2.0;
  43633. _this.noRotationConstraint = false;
  43634. _this.lockedTarget = null;
  43635. _this._currentTarget = BABYLON.Vector3.Zero();
  43636. _this._viewMatrix = BABYLON.Matrix.Zero();
  43637. _this._camMatrix = BABYLON.Matrix.Zero();
  43638. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43639. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43640. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43641. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43642. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43643. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43644. _this._tempMatrix = BABYLON.Matrix.Zero();
  43645. return _this;
  43646. }
  43647. TargetCamera.prototype.getFrontPosition = function (distance) {
  43648. this.getWorldMatrix();
  43649. var direction = this.getTarget().subtract(this.position);
  43650. direction.normalize();
  43651. direction.scaleInPlace(distance);
  43652. return this.globalPosition.add(direction);
  43653. };
  43654. TargetCamera.prototype._getLockedTargetPosition = function () {
  43655. if (!this.lockedTarget) {
  43656. return null;
  43657. }
  43658. if (this.lockedTarget.absolutePosition) {
  43659. this.lockedTarget.computeWorldMatrix();
  43660. }
  43661. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43662. };
  43663. TargetCamera.prototype.storeState = function () {
  43664. this._storedPosition = this.position.clone();
  43665. this._storedRotation = this.rotation.clone();
  43666. if (this.rotationQuaternion) {
  43667. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43668. }
  43669. return _super.prototype.storeState.call(this);
  43670. };
  43671. /**
  43672. * Restored camera state. You must call storeState() first
  43673. */
  43674. TargetCamera.prototype._restoreStateValues = function () {
  43675. if (!_super.prototype._restoreStateValues.call(this)) {
  43676. return false;
  43677. }
  43678. this.position = this._storedPosition.clone();
  43679. this.rotation = this._storedRotation.clone();
  43680. if (this.rotationQuaternion) {
  43681. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43682. }
  43683. this.cameraDirection.copyFromFloats(0, 0, 0);
  43684. this.cameraRotation.copyFromFloats(0, 0);
  43685. return true;
  43686. };
  43687. // Cache
  43688. TargetCamera.prototype._initCache = function () {
  43689. _super.prototype._initCache.call(this);
  43690. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43691. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43692. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43693. };
  43694. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43695. if (!ignoreParentClass) {
  43696. _super.prototype._updateCache.call(this);
  43697. }
  43698. var lockedTargetPosition = this._getLockedTargetPosition();
  43699. if (!lockedTargetPosition) {
  43700. this._cache.lockedTarget = null;
  43701. }
  43702. else {
  43703. if (!this._cache.lockedTarget) {
  43704. this._cache.lockedTarget = lockedTargetPosition.clone();
  43705. }
  43706. else {
  43707. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43708. }
  43709. }
  43710. this._cache.rotation.copyFrom(this.rotation);
  43711. if (this.rotationQuaternion)
  43712. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43713. };
  43714. // Synchronized
  43715. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43716. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43717. return false;
  43718. }
  43719. var lockedTargetPosition = this._getLockedTargetPosition();
  43720. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43721. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43722. };
  43723. // Methods
  43724. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43725. var engine = this.getEngine();
  43726. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43727. };
  43728. // Target
  43729. TargetCamera.prototype.setTarget = function (target) {
  43730. this.upVector.normalize();
  43731. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43732. this._camMatrix.invert();
  43733. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43734. var vDir = target.subtract(this.position);
  43735. if (vDir.x >= 0.0) {
  43736. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43737. }
  43738. else {
  43739. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43740. }
  43741. this.rotation.z = 0;
  43742. if (isNaN(this.rotation.x)) {
  43743. this.rotation.x = 0;
  43744. }
  43745. if (isNaN(this.rotation.y)) {
  43746. this.rotation.y = 0;
  43747. }
  43748. if (isNaN(this.rotation.z)) {
  43749. this.rotation.z = 0;
  43750. }
  43751. if (this.rotationQuaternion) {
  43752. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43753. }
  43754. };
  43755. /**
  43756. * Return the current target position of the camera. This value is expressed in local space.
  43757. */
  43758. TargetCamera.prototype.getTarget = function () {
  43759. return this._currentTarget;
  43760. };
  43761. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43762. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43763. };
  43764. TargetCamera.prototype._updatePosition = function () {
  43765. if (this.parent) {
  43766. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43767. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43768. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43769. return;
  43770. }
  43771. this.position.addInPlace(this.cameraDirection);
  43772. };
  43773. TargetCamera.prototype._checkInputs = function () {
  43774. var needToMove = this._decideIfNeedsToMove();
  43775. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43776. // Move
  43777. if (needToMove) {
  43778. this._updatePosition();
  43779. }
  43780. // Rotate
  43781. if (needToRotate) {
  43782. this.rotation.x += this.cameraRotation.x;
  43783. this.rotation.y += this.cameraRotation.y;
  43784. //rotate, if quaternion is set and rotation was used
  43785. if (this.rotationQuaternion) {
  43786. var len = this.rotation.lengthSquared();
  43787. if (len) {
  43788. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43789. }
  43790. }
  43791. if (!this.noRotationConstraint) {
  43792. var limit = (Math.PI / 2) * 0.95;
  43793. if (this.rotation.x > limit)
  43794. this.rotation.x = limit;
  43795. if (this.rotation.x < -limit)
  43796. this.rotation.x = -limit;
  43797. }
  43798. }
  43799. // Inertia
  43800. if (needToMove) {
  43801. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43802. this.cameraDirection.x = 0;
  43803. }
  43804. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43805. this.cameraDirection.y = 0;
  43806. }
  43807. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43808. this.cameraDirection.z = 0;
  43809. }
  43810. this.cameraDirection.scaleInPlace(this.inertia);
  43811. }
  43812. if (needToRotate) {
  43813. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43814. this.cameraRotation.x = 0;
  43815. }
  43816. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43817. this.cameraRotation.y = 0;
  43818. }
  43819. this.cameraRotation.scaleInPlace(this.inertia);
  43820. }
  43821. _super.prototype._checkInputs.call(this);
  43822. };
  43823. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43824. if (this.rotationQuaternion) {
  43825. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43826. }
  43827. else {
  43828. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43829. }
  43830. //update the up vector!
  43831. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43832. };
  43833. TargetCamera.prototype._getViewMatrix = function () {
  43834. if (this.lockedTarget) {
  43835. this.setTarget(this._getLockedTargetPosition());
  43836. }
  43837. // Compute
  43838. this._updateCameraRotationMatrix();
  43839. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43840. // Computing target and final matrix
  43841. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43842. if (this.getScene().useRightHandedSystem) {
  43843. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43844. }
  43845. else {
  43846. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43847. }
  43848. return this._viewMatrix;
  43849. };
  43850. /**
  43851. * @override
  43852. * Override Camera.createRigCamera
  43853. */
  43854. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43855. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43856. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43857. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43858. if (!this.rotationQuaternion) {
  43859. this.rotationQuaternion = new BABYLON.Quaternion();
  43860. }
  43861. rigCamera._cameraRigParams = {};
  43862. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43863. }
  43864. return rigCamera;
  43865. }
  43866. return null;
  43867. };
  43868. /**
  43869. * @override
  43870. * Override Camera._updateRigCameras
  43871. */
  43872. TargetCamera.prototype._updateRigCameras = function () {
  43873. var camLeft = this._rigCameras[0];
  43874. var camRight = this._rigCameras[1];
  43875. switch (this.cameraRigMode) {
  43876. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43877. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43878. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43879. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43880. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43881. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43882. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43883. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43884. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43885. camLeft.setTarget(this.getTarget());
  43886. camRight.setTarget(this.getTarget());
  43887. break;
  43888. case BABYLON.Camera.RIG_MODE_VR:
  43889. if (camLeft.rotationQuaternion) {
  43890. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43891. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43892. }
  43893. else {
  43894. camLeft.rotation.copyFrom(this.rotation);
  43895. camRight.rotation.copyFrom(this.rotation);
  43896. }
  43897. camLeft.position.copyFrom(this.position);
  43898. camRight.position.copyFrom(this.position);
  43899. break;
  43900. }
  43901. _super.prototype._updateRigCameras.call(this);
  43902. };
  43903. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43904. if (!this._rigCamTransformMatrix) {
  43905. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43906. }
  43907. var target = this.getTarget();
  43908. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43909. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43910. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43911. };
  43912. TargetCamera.prototype.getClassName = function () {
  43913. return "TargetCamera";
  43914. };
  43915. __decorate([
  43916. BABYLON.serializeAsVector3()
  43917. ], TargetCamera.prototype, "rotation", void 0);
  43918. __decorate([
  43919. BABYLON.serialize()
  43920. ], TargetCamera.prototype, "speed", void 0);
  43921. __decorate([
  43922. BABYLON.serializeAsMeshReference("lockedTargetId")
  43923. ], TargetCamera.prototype, "lockedTarget", void 0);
  43924. return TargetCamera;
  43925. }(BABYLON.Camera));
  43926. BABYLON.TargetCamera = TargetCamera;
  43927. })(BABYLON || (BABYLON = {}));
  43928. //# sourceMappingURL=babylon.targetCamera.js.map
  43929. "use strict";
  43930. var BABYLON;
  43931. (function (BABYLON) {
  43932. var FreeCameraMouseInput = /** @class */ (function () {
  43933. function FreeCameraMouseInput(touchEnabled) {
  43934. if (touchEnabled === void 0) { touchEnabled = true; }
  43935. this.touchEnabled = touchEnabled;
  43936. this.buttons = [0, 1, 2];
  43937. this.angularSensibility = 2000.0;
  43938. this.previousPosition = null;
  43939. }
  43940. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43941. var _this = this;
  43942. var engine = this.camera.getEngine();
  43943. if (!this._pointerInput) {
  43944. this._pointerInput = function (p, s) {
  43945. var evt = p.event;
  43946. if (engine.isInVRExclusivePointerMode) {
  43947. return;
  43948. }
  43949. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43950. return;
  43951. }
  43952. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43953. return;
  43954. }
  43955. var srcElement = (evt.srcElement || evt.target);
  43956. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43957. try {
  43958. srcElement.setPointerCapture(evt.pointerId);
  43959. }
  43960. catch (e) {
  43961. //Nothing to do with the error. Execution will continue.
  43962. }
  43963. _this.previousPosition = {
  43964. x: evt.clientX,
  43965. y: evt.clientY
  43966. };
  43967. if (!noPreventDefault) {
  43968. evt.preventDefault();
  43969. element.focus();
  43970. }
  43971. }
  43972. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43973. try {
  43974. srcElement.releasePointerCapture(evt.pointerId);
  43975. }
  43976. catch (e) {
  43977. //Nothing to do with the error.
  43978. }
  43979. _this.previousPosition = null;
  43980. if (!noPreventDefault) {
  43981. evt.preventDefault();
  43982. }
  43983. }
  43984. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43985. if (!_this.previousPosition || engine.isPointerLock) {
  43986. return;
  43987. }
  43988. var offsetX = evt.clientX - _this.previousPosition.x;
  43989. var offsetY = evt.clientY - _this.previousPosition.y;
  43990. if (_this.camera.getScene().useRightHandedSystem) {
  43991. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43992. }
  43993. else {
  43994. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43995. }
  43996. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43997. _this.previousPosition = {
  43998. x: evt.clientX,
  43999. y: evt.clientY
  44000. };
  44001. if (!noPreventDefault) {
  44002. evt.preventDefault();
  44003. }
  44004. }
  44005. };
  44006. }
  44007. this._onMouseMove = function (evt) {
  44008. if (!engine.isPointerLock) {
  44009. return;
  44010. }
  44011. if (engine.isInVRExclusivePointerMode) {
  44012. return;
  44013. }
  44014. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44015. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44016. if (_this.camera.getScene().useRightHandedSystem) {
  44017. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44018. }
  44019. else {
  44020. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44021. }
  44022. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44023. _this.previousPosition = null;
  44024. if (!noPreventDefault) {
  44025. evt.preventDefault();
  44026. }
  44027. };
  44028. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44029. element.addEventListener("mousemove", this._onMouseMove, false);
  44030. };
  44031. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44032. if (this._observer && element) {
  44033. this.camera.getScene().onPointerObservable.remove(this._observer);
  44034. if (this._onMouseMove) {
  44035. element.removeEventListener("mousemove", this._onMouseMove);
  44036. }
  44037. this._observer = null;
  44038. this._onMouseMove = null;
  44039. this.previousPosition = null;
  44040. }
  44041. };
  44042. FreeCameraMouseInput.prototype.getClassName = function () {
  44043. return "FreeCameraMouseInput";
  44044. };
  44045. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44046. return "mouse";
  44047. };
  44048. __decorate([
  44049. BABYLON.serialize()
  44050. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44051. __decorate([
  44052. BABYLON.serialize()
  44053. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44054. return FreeCameraMouseInput;
  44055. }());
  44056. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44057. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44058. })(BABYLON || (BABYLON = {}));
  44059. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44060. "use strict";
  44061. var BABYLON;
  44062. (function (BABYLON) {
  44063. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44064. function FreeCameraKeyboardMoveInput() {
  44065. this._keys = new Array();
  44066. this.keysUp = [38];
  44067. this.keysDown = [40];
  44068. this.keysLeft = [37];
  44069. this.keysRight = [39];
  44070. }
  44071. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44072. var _this = this;
  44073. if (this._onCanvasBlurObserver) {
  44074. return;
  44075. }
  44076. this._scene = this.camera.getScene();
  44077. this._engine = this._scene.getEngine();
  44078. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44079. _this._keys = [];
  44080. });
  44081. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44082. var evt = info.event;
  44083. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44084. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44085. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44086. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44087. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44088. var index = _this._keys.indexOf(evt.keyCode);
  44089. if (index === -1) {
  44090. _this._keys.push(evt.keyCode);
  44091. }
  44092. if (!noPreventDefault) {
  44093. evt.preventDefault();
  44094. }
  44095. }
  44096. }
  44097. else {
  44098. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44099. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44100. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44101. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44102. var index = _this._keys.indexOf(evt.keyCode);
  44103. if (index >= 0) {
  44104. _this._keys.splice(index, 1);
  44105. }
  44106. if (!noPreventDefault) {
  44107. evt.preventDefault();
  44108. }
  44109. }
  44110. }
  44111. });
  44112. };
  44113. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44114. if (this._scene) {
  44115. if (this._onKeyboardObserver) {
  44116. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44117. }
  44118. if (this._onCanvasBlurObserver) {
  44119. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44120. }
  44121. this._onKeyboardObserver = null;
  44122. this._onCanvasBlurObserver = null;
  44123. }
  44124. this._keys = [];
  44125. };
  44126. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44127. if (this._onKeyboardObserver) {
  44128. var camera = this.camera;
  44129. // Keyboard
  44130. for (var index = 0; index < this._keys.length; index++) {
  44131. var keyCode = this._keys[index];
  44132. var speed = camera._computeLocalCameraSpeed();
  44133. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44134. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44135. }
  44136. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44137. camera._localDirection.copyFromFloats(0, 0, speed);
  44138. }
  44139. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44140. camera._localDirection.copyFromFloats(speed, 0, 0);
  44141. }
  44142. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44143. camera._localDirection.copyFromFloats(0, 0, -speed);
  44144. }
  44145. if (camera.getScene().useRightHandedSystem) {
  44146. camera._localDirection.z *= -1;
  44147. }
  44148. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44149. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44150. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44151. }
  44152. }
  44153. };
  44154. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44155. return "FreeCameraKeyboardMoveInput";
  44156. };
  44157. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44158. this._keys = [];
  44159. };
  44160. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44161. return "keyboard";
  44162. };
  44163. __decorate([
  44164. BABYLON.serialize()
  44165. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44166. __decorate([
  44167. BABYLON.serialize()
  44168. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44169. __decorate([
  44170. BABYLON.serialize()
  44171. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44172. __decorate([
  44173. BABYLON.serialize()
  44174. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44175. return FreeCameraKeyboardMoveInput;
  44176. }());
  44177. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44178. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44179. })(BABYLON || (BABYLON = {}));
  44180. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44181. "use strict";
  44182. var BABYLON;
  44183. (function (BABYLON) {
  44184. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44185. __extends(FreeCameraInputsManager, _super);
  44186. function FreeCameraInputsManager(camera) {
  44187. return _super.call(this, camera) || this;
  44188. }
  44189. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44190. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44191. return this;
  44192. };
  44193. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44194. if (touchEnabled === void 0) { touchEnabled = true; }
  44195. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44196. return this;
  44197. };
  44198. FreeCameraInputsManager.prototype.addGamepad = function () {
  44199. this.add(new BABYLON.FreeCameraGamepadInput());
  44200. return this;
  44201. };
  44202. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44203. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44204. return this;
  44205. };
  44206. FreeCameraInputsManager.prototype.addTouch = function () {
  44207. this.add(new BABYLON.FreeCameraTouchInput());
  44208. return this;
  44209. };
  44210. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44211. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44212. return this;
  44213. };
  44214. return FreeCameraInputsManager;
  44215. }(BABYLON.CameraInputsManager));
  44216. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44217. })(BABYLON || (BABYLON = {}));
  44218. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44219. "use strict";
  44220. var BABYLON;
  44221. (function (BABYLON) {
  44222. var FreeCamera = /** @class */ (function (_super) {
  44223. __extends(FreeCamera, _super);
  44224. function FreeCamera(name, position, scene) {
  44225. var _this = _super.call(this, name, position, scene) || this;
  44226. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44227. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44228. _this.checkCollisions = false;
  44229. _this.applyGravity = false;
  44230. _this._needMoveForGravity = false;
  44231. _this._oldPosition = BABYLON.Vector3.Zero();
  44232. _this._diffPosition = BABYLON.Vector3.Zero();
  44233. _this._newPosition = BABYLON.Vector3.Zero();
  44234. // Collisions
  44235. _this._collisionMask = -1;
  44236. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44237. if (collidedMesh === void 0) { collidedMesh = null; }
  44238. //TODO move this to the collision coordinator!
  44239. if (_this.getScene().workerCollisions)
  44240. newPosition.multiplyInPlace(_this._collider._radius);
  44241. var updatePosition = function (newPos) {
  44242. _this._newPosition.copyFrom(newPos);
  44243. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44244. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44245. _this.position.addInPlace(_this._diffPosition);
  44246. if (_this.onCollide && collidedMesh) {
  44247. _this.onCollide(collidedMesh);
  44248. }
  44249. }
  44250. };
  44251. updatePosition(newPosition);
  44252. };
  44253. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44254. _this.inputs.addKeyboard().addMouse();
  44255. return _this;
  44256. }
  44257. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44258. //-- begin properties for backward compatibility for inputs
  44259. /**
  44260. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44261. * Higher values reduce sensitivity.
  44262. */
  44263. get: function () {
  44264. var mouse = this.inputs.attached["mouse"];
  44265. if (mouse)
  44266. return mouse.angularSensibility;
  44267. return 0;
  44268. },
  44269. /**
  44270. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44271. * Higher values reduce sensitivity.
  44272. */
  44273. set: function (value) {
  44274. var mouse = this.inputs.attached["mouse"];
  44275. if (mouse)
  44276. mouse.angularSensibility = value;
  44277. },
  44278. enumerable: true,
  44279. configurable: true
  44280. });
  44281. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44282. get: function () {
  44283. var keyboard = this.inputs.attached["keyboard"];
  44284. if (keyboard)
  44285. return keyboard.keysUp;
  44286. return [];
  44287. },
  44288. set: function (value) {
  44289. var keyboard = this.inputs.attached["keyboard"];
  44290. if (keyboard)
  44291. keyboard.keysUp = value;
  44292. },
  44293. enumerable: true,
  44294. configurable: true
  44295. });
  44296. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44297. get: function () {
  44298. var keyboard = this.inputs.attached["keyboard"];
  44299. if (keyboard)
  44300. return keyboard.keysDown;
  44301. return [];
  44302. },
  44303. set: function (value) {
  44304. var keyboard = this.inputs.attached["keyboard"];
  44305. if (keyboard)
  44306. keyboard.keysDown = value;
  44307. },
  44308. enumerable: true,
  44309. configurable: true
  44310. });
  44311. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44312. get: function () {
  44313. var keyboard = this.inputs.attached["keyboard"];
  44314. if (keyboard)
  44315. return keyboard.keysLeft;
  44316. return [];
  44317. },
  44318. set: function (value) {
  44319. var keyboard = this.inputs.attached["keyboard"];
  44320. if (keyboard)
  44321. keyboard.keysLeft = value;
  44322. },
  44323. enumerable: true,
  44324. configurable: true
  44325. });
  44326. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44327. get: function () {
  44328. var keyboard = this.inputs.attached["keyboard"];
  44329. if (keyboard)
  44330. return keyboard.keysRight;
  44331. return [];
  44332. },
  44333. set: function (value) {
  44334. var keyboard = this.inputs.attached["keyboard"];
  44335. if (keyboard)
  44336. keyboard.keysRight = value;
  44337. },
  44338. enumerable: true,
  44339. configurable: true
  44340. });
  44341. // Controls
  44342. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44343. this.inputs.attachElement(element, noPreventDefault);
  44344. };
  44345. FreeCamera.prototype.detachControl = function (element) {
  44346. this.inputs.detachElement(element);
  44347. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44348. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44349. };
  44350. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44351. get: function () {
  44352. return this._collisionMask;
  44353. },
  44354. set: function (mask) {
  44355. this._collisionMask = !isNaN(mask) ? mask : -1;
  44356. },
  44357. enumerable: true,
  44358. configurable: true
  44359. });
  44360. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44361. var globalPosition;
  44362. if (this.parent) {
  44363. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44364. }
  44365. else {
  44366. globalPosition = this.position;
  44367. }
  44368. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44369. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44370. if (!this._collider) {
  44371. this._collider = new BABYLON.Collider();
  44372. }
  44373. this._collider._radius = this.ellipsoid;
  44374. this._collider.collisionMask = this._collisionMask;
  44375. //no need for clone, as long as gravity is not on.
  44376. var actualDisplacement = displacement;
  44377. //add gravity to the direction to prevent the dual-collision checking
  44378. if (this.applyGravity) {
  44379. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44380. actualDisplacement = displacement.add(this.getScene().gravity);
  44381. }
  44382. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44383. };
  44384. FreeCamera.prototype._checkInputs = function () {
  44385. if (!this._localDirection) {
  44386. this._localDirection = BABYLON.Vector3.Zero();
  44387. this._transformedDirection = BABYLON.Vector3.Zero();
  44388. }
  44389. this.inputs.checkInputs();
  44390. _super.prototype._checkInputs.call(this);
  44391. };
  44392. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44393. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44394. };
  44395. FreeCamera.prototype._updatePosition = function () {
  44396. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44397. this._collideWithWorld(this.cameraDirection);
  44398. }
  44399. else {
  44400. _super.prototype._updatePosition.call(this);
  44401. }
  44402. };
  44403. FreeCamera.prototype.dispose = function () {
  44404. this.inputs.clear();
  44405. _super.prototype.dispose.call(this);
  44406. };
  44407. FreeCamera.prototype.getClassName = function () {
  44408. return "FreeCamera";
  44409. };
  44410. __decorate([
  44411. BABYLON.serializeAsVector3()
  44412. ], FreeCamera.prototype, "ellipsoid", void 0);
  44413. __decorate([
  44414. BABYLON.serializeAsVector3()
  44415. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44416. __decorate([
  44417. BABYLON.serialize()
  44418. ], FreeCamera.prototype, "checkCollisions", void 0);
  44419. __decorate([
  44420. BABYLON.serialize()
  44421. ], FreeCamera.prototype, "applyGravity", void 0);
  44422. return FreeCamera;
  44423. }(BABYLON.TargetCamera));
  44424. BABYLON.FreeCamera = FreeCamera;
  44425. })(BABYLON || (BABYLON = {}));
  44426. //# sourceMappingURL=babylon.freeCamera.js.map
  44427. "use strict";
  44428. var BABYLON;
  44429. (function (BABYLON) {
  44430. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44431. function ArcRotateCameraKeyboardMoveInput() {
  44432. this._keys = new Array();
  44433. this.keysUp = [38];
  44434. this.keysDown = [40];
  44435. this.keysLeft = [37];
  44436. this.keysRight = [39];
  44437. this.keysReset = [220];
  44438. this.panningSensibility = 50.0;
  44439. this.zoomingSensibility = 25.0;
  44440. this.useAltToZoom = true;
  44441. }
  44442. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44443. var _this = this;
  44444. if (this._onCanvasBlurObserver) {
  44445. return;
  44446. }
  44447. this._scene = this.camera.getScene();
  44448. this._engine = this._scene.getEngine();
  44449. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44450. _this._keys = [];
  44451. });
  44452. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44453. var evt = info.event;
  44454. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44455. _this._ctrlPressed = evt.ctrlKey;
  44456. _this._altPressed = evt.altKey;
  44457. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44458. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44459. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44460. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44461. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44462. var index = _this._keys.indexOf(evt.keyCode);
  44463. if (index === -1) {
  44464. _this._keys.push(evt.keyCode);
  44465. }
  44466. if (evt.preventDefault) {
  44467. if (!noPreventDefault) {
  44468. evt.preventDefault();
  44469. }
  44470. }
  44471. }
  44472. }
  44473. else {
  44474. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44475. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44476. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44477. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44478. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44479. var index = _this._keys.indexOf(evt.keyCode);
  44480. if (index >= 0) {
  44481. _this._keys.splice(index, 1);
  44482. }
  44483. if (evt.preventDefault) {
  44484. if (!noPreventDefault) {
  44485. evt.preventDefault();
  44486. }
  44487. }
  44488. }
  44489. }
  44490. });
  44491. };
  44492. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44493. if (this._scene) {
  44494. if (this._onKeyboardObserver) {
  44495. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44496. }
  44497. if (this._onCanvasBlurObserver) {
  44498. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44499. }
  44500. this._onKeyboardObserver = null;
  44501. this._onCanvasBlurObserver = null;
  44502. }
  44503. this._keys = [];
  44504. };
  44505. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44506. if (this._onKeyboardObserver) {
  44507. var camera = this.camera;
  44508. for (var index = 0; index < this._keys.length; index++) {
  44509. var keyCode = this._keys[index];
  44510. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44511. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44512. camera.inertialPanningX -= 1 / this.panningSensibility;
  44513. }
  44514. else {
  44515. camera.inertialAlphaOffset -= 0.01;
  44516. }
  44517. }
  44518. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44519. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44520. camera.inertialPanningY += 1 / this.panningSensibility;
  44521. }
  44522. else if (this._altPressed && this.useAltToZoom) {
  44523. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44524. }
  44525. else {
  44526. camera.inertialBetaOffset -= 0.01;
  44527. }
  44528. }
  44529. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44530. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44531. camera.inertialPanningX += 1 / this.panningSensibility;
  44532. }
  44533. else {
  44534. camera.inertialAlphaOffset += 0.01;
  44535. }
  44536. }
  44537. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44538. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44539. camera.inertialPanningY -= 1 / this.panningSensibility;
  44540. }
  44541. else if (this._altPressed && this.useAltToZoom) {
  44542. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44543. }
  44544. else {
  44545. camera.inertialBetaOffset += 0.01;
  44546. }
  44547. }
  44548. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44549. camera.restoreState();
  44550. }
  44551. }
  44552. }
  44553. };
  44554. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44555. return "ArcRotateCameraKeyboardMoveInput";
  44556. };
  44557. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44558. return "keyboard";
  44559. };
  44560. __decorate([
  44561. BABYLON.serialize()
  44562. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44563. __decorate([
  44564. BABYLON.serialize()
  44565. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44566. __decorate([
  44567. BABYLON.serialize()
  44568. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44569. __decorate([
  44570. BABYLON.serialize()
  44571. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44572. __decorate([
  44573. BABYLON.serialize()
  44574. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44575. __decorate([
  44576. BABYLON.serialize()
  44577. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44578. __decorate([
  44579. BABYLON.serialize()
  44580. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44581. __decorate([
  44582. BABYLON.serialize()
  44583. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44584. return ArcRotateCameraKeyboardMoveInput;
  44585. }());
  44586. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44587. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44588. })(BABYLON || (BABYLON = {}));
  44589. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44590. "use strict";
  44591. var BABYLON;
  44592. (function (BABYLON) {
  44593. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44594. function ArcRotateCameraMouseWheelInput() {
  44595. this.wheelPrecision = 3.0;
  44596. /**
  44597. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44598. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44599. */
  44600. this.wheelDeltaPercentage = 0;
  44601. }
  44602. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44603. var _this = this;
  44604. this._wheel = function (p, s) {
  44605. //sanity check - this should be a PointerWheel event.
  44606. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44607. return;
  44608. var event = p.event;
  44609. var delta = 0;
  44610. if (event.wheelDelta) {
  44611. if (_this.wheelDeltaPercentage) {
  44612. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  44613. if (event.wheelDelta > 0) {
  44614. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  44615. }
  44616. else {
  44617. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  44618. }
  44619. }
  44620. else {
  44621. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  44622. }
  44623. }
  44624. else if (event.detail) {
  44625. delta = -event.detail / _this.wheelPrecision;
  44626. }
  44627. if (delta)
  44628. _this.camera.inertialRadiusOffset += delta;
  44629. if (event.preventDefault) {
  44630. if (!noPreventDefault) {
  44631. event.preventDefault();
  44632. }
  44633. }
  44634. };
  44635. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44636. };
  44637. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44638. if (this._observer && element) {
  44639. this.camera.getScene().onPointerObservable.remove(this._observer);
  44640. this._observer = null;
  44641. this._wheel = null;
  44642. }
  44643. };
  44644. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44645. return "ArcRotateCameraMouseWheelInput";
  44646. };
  44647. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44648. return "mousewheel";
  44649. };
  44650. __decorate([
  44651. BABYLON.serialize()
  44652. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44653. __decorate([
  44654. BABYLON.serialize()
  44655. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44656. return ArcRotateCameraMouseWheelInput;
  44657. }());
  44658. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44659. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44660. })(BABYLON || (BABYLON = {}));
  44661. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44662. "use strict";
  44663. var BABYLON;
  44664. (function (BABYLON) {
  44665. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44666. function ArcRotateCameraPointersInput() {
  44667. this.buttons = [0, 1, 2];
  44668. this.angularSensibilityX = 1000.0;
  44669. this.angularSensibilityY = 1000.0;
  44670. this.pinchPrecision = 12.0;
  44671. /**
  44672. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44673. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44674. */
  44675. this.pinchDeltaPercentage = 0;
  44676. this.panningSensibility = 1000.0;
  44677. this.multiTouchPanning = true;
  44678. this.multiTouchPanAndZoom = true;
  44679. this._isPanClick = false;
  44680. this.pinchInwards = true;
  44681. }
  44682. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44683. var _this = this;
  44684. var engine = this.camera.getEngine();
  44685. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44686. var pointA = null;
  44687. var pointB = null;
  44688. var previousPinchSquaredDistance = 0;
  44689. var initialDistance = 0;
  44690. var twoFingerActivityCount = 0;
  44691. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44692. this._pointerInput = function (p, s) {
  44693. var evt = p.event;
  44694. var isTouch = p.event.pointerType === "touch";
  44695. if (engine.isInVRExclusivePointerMode) {
  44696. return;
  44697. }
  44698. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44699. return;
  44700. }
  44701. var srcElement = (evt.srcElement || evt.target);
  44702. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44703. try {
  44704. srcElement.setPointerCapture(evt.pointerId);
  44705. }
  44706. catch (e) {
  44707. //Nothing to do with the error. Execution will continue.
  44708. }
  44709. // Manage panning with pan button click
  44710. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44711. // manage pointers
  44712. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44713. if (pointA === null) {
  44714. pointA = cacheSoloPointer;
  44715. }
  44716. else if (pointB === null) {
  44717. pointB = cacheSoloPointer;
  44718. }
  44719. if (!noPreventDefault) {
  44720. evt.preventDefault();
  44721. element.focus();
  44722. }
  44723. }
  44724. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44725. _this.camera.restoreState();
  44726. }
  44727. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44728. try {
  44729. srcElement.releasePointerCapture(evt.pointerId);
  44730. }
  44731. catch (e) {
  44732. //Nothing to do with the error.
  44733. }
  44734. cacheSoloPointer = null;
  44735. previousPinchSquaredDistance = 0;
  44736. previousMultiTouchPanPosition.isPaning = false;
  44737. previousMultiTouchPanPosition.isPinching = false;
  44738. twoFingerActivityCount = 0;
  44739. initialDistance = 0;
  44740. if (!isTouch) {
  44741. pointB = null; // Mouse and pen are mono pointer
  44742. }
  44743. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44744. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44745. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44746. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44747. if (engine.badOS) {
  44748. pointA = pointB = null;
  44749. }
  44750. else {
  44751. //only remove the impacted pointer in case of multitouch allowing on most
  44752. //platforms switching from rotate to zoom and pan seamlessly.
  44753. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44754. pointA = pointB;
  44755. pointB = null;
  44756. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44757. }
  44758. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44759. pointB = null;
  44760. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44761. }
  44762. else {
  44763. pointA = pointB = null;
  44764. }
  44765. }
  44766. if (!noPreventDefault) {
  44767. evt.preventDefault();
  44768. }
  44769. }
  44770. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44771. if (!noPreventDefault) {
  44772. evt.preventDefault();
  44773. }
  44774. // One button down
  44775. if (pointA && pointB === null && cacheSoloPointer) {
  44776. if (_this.panningSensibility !== 0 &&
  44777. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44778. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44779. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44780. }
  44781. else {
  44782. var offsetX = evt.clientX - cacheSoloPointer.x;
  44783. var offsetY = evt.clientY - cacheSoloPointer.y;
  44784. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44785. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44786. }
  44787. cacheSoloPointer.x = evt.clientX;
  44788. cacheSoloPointer.y = evt.clientY;
  44789. }
  44790. else if (pointA && pointB) {
  44791. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44792. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44793. ed.x = evt.clientX;
  44794. ed.y = evt.clientY;
  44795. var direction = _this.pinchInwards ? 1 : -1;
  44796. var distX = pointA.x - pointB.x;
  44797. var distY = pointA.y - pointB.y;
  44798. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44799. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44800. if (previousPinchSquaredDistance === 0) {
  44801. initialDistance = pinchDistance;
  44802. previousPinchSquaredDistance = pinchSquaredDistance;
  44803. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44804. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44805. return;
  44806. }
  44807. if (_this.multiTouchPanAndZoom) {
  44808. if (_this.pinchDeltaPercentage) {
  44809. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44810. }
  44811. else {
  44812. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44813. (_this.pinchPrecision *
  44814. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44815. direction);
  44816. }
  44817. if (_this.panningSensibility !== 0) {
  44818. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44819. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44820. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44821. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44822. previousMultiTouchPanPosition.x = pointersCenterX;
  44823. previousMultiTouchPanPosition.y = pointersCenterY;
  44824. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44825. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44826. }
  44827. }
  44828. else {
  44829. twoFingerActivityCount++;
  44830. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44831. if (_this.pinchDeltaPercentage) {
  44832. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44833. }
  44834. else {
  44835. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44836. (_this.pinchPrecision *
  44837. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44838. direction);
  44839. }
  44840. previousMultiTouchPanPosition.isPaning = false;
  44841. previousMultiTouchPanPosition.isPinching = true;
  44842. }
  44843. else {
  44844. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44845. if (!previousMultiTouchPanPosition.isPaning) {
  44846. previousMultiTouchPanPosition.isPaning = true;
  44847. previousMultiTouchPanPosition.isPinching = false;
  44848. previousMultiTouchPanPosition.x = ed.x;
  44849. previousMultiTouchPanPosition.y = ed.y;
  44850. return;
  44851. }
  44852. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44853. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44854. }
  44855. }
  44856. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44857. previousMultiTouchPanPosition.x = ed.x;
  44858. previousMultiTouchPanPosition.y = ed.y;
  44859. }
  44860. }
  44861. previousPinchSquaredDistance = pinchSquaredDistance;
  44862. }
  44863. }
  44864. };
  44865. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44866. this._onContextMenu = function (evt) {
  44867. evt.preventDefault();
  44868. };
  44869. if (!this.camera._useCtrlForPanning) {
  44870. element.addEventListener("contextmenu", this._onContextMenu, false);
  44871. }
  44872. this._onLostFocus = function () {
  44873. //this._keys = [];
  44874. pointA = pointB = null;
  44875. previousPinchSquaredDistance = 0;
  44876. previousMultiTouchPanPosition.isPaning = false;
  44877. previousMultiTouchPanPosition.isPinching = false;
  44878. twoFingerActivityCount = 0;
  44879. cacheSoloPointer = null;
  44880. initialDistance = 0;
  44881. };
  44882. this._onMouseMove = function (evt) {
  44883. if (!engine.isPointerLock) {
  44884. return;
  44885. }
  44886. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44887. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44888. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44889. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44890. if (!noPreventDefault) {
  44891. evt.preventDefault();
  44892. }
  44893. };
  44894. this._onGestureStart = function (e) {
  44895. if (window.MSGesture === undefined) {
  44896. return;
  44897. }
  44898. if (!_this._MSGestureHandler) {
  44899. _this._MSGestureHandler = new MSGesture();
  44900. _this._MSGestureHandler.target = element;
  44901. }
  44902. _this._MSGestureHandler.addPointer(e.pointerId);
  44903. };
  44904. this._onGesture = function (e) {
  44905. _this.camera.radius *= e.scale;
  44906. if (e.preventDefault) {
  44907. if (!noPreventDefault) {
  44908. e.stopPropagation();
  44909. e.preventDefault();
  44910. }
  44911. }
  44912. };
  44913. element.addEventListener("mousemove", this._onMouseMove, false);
  44914. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44915. element.addEventListener("MSGestureChange", this._onGesture, false);
  44916. BABYLON.Tools.RegisterTopRootEvents([
  44917. { name: "blur", handler: this._onLostFocus }
  44918. ]);
  44919. };
  44920. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44921. if (this._onLostFocus) {
  44922. BABYLON.Tools.UnregisterTopRootEvents([
  44923. { name: "blur", handler: this._onLostFocus }
  44924. ]);
  44925. }
  44926. if (element && this._observer) {
  44927. this.camera.getScene().onPointerObservable.remove(this._observer);
  44928. this._observer = null;
  44929. if (this._onContextMenu) {
  44930. element.removeEventListener("contextmenu", this._onContextMenu);
  44931. }
  44932. if (this._onMouseMove) {
  44933. element.removeEventListener("mousemove", this._onMouseMove);
  44934. }
  44935. if (this._onGestureStart) {
  44936. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44937. }
  44938. if (this._onGesture) {
  44939. element.removeEventListener("MSGestureChange", this._onGesture);
  44940. }
  44941. this._isPanClick = false;
  44942. this.pinchInwards = true;
  44943. this._onMouseMove = null;
  44944. this._onGestureStart = null;
  44945. this._onGesture = null;
  44946. this._MSGestureHandler = null;
  44947. this._onLostFocus = null;
  44948. this._onContextMenu = null;
  44949. }
  44950. };
  44951. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44952. return "ArcRotateCameraPointersInput";
  44953. };
  44954. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44955. return "pointers";
  44956. };
  44957. __decorate([
  44958. BABYLON.serialize()
  44959. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44960. __decorate([
  44961. BABYLON.serialize()
  44962. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44963. __decorate([
  44964. BABYLON.serialize()
  44965. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44966. __decorate([
  44967. BABYLON.serialize()
  44968. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44969. __decorate([
  44970. BABYLON.serialize()
  44971. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44972. __decorate([
  44973. BABYLON.serialize()
  44974. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44975. __decorate([
  44976. BABYLON.serialize()
  44977. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44978. __decorate([
  44979. BABYLON.serialize()
  44980. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44981. return ArcRotateCameraPointersInput;
  44982. }());
  44983. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44984. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44985. })(BABYLON || (BABYLON = {}));
  44986. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44987. "use strict";
  44988. var BABYLON;
  44989. (function (BABYLON) {
  44990. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44991. __extends(ArcRotateCameraInputsManager, _super);
  44992. function ArcRotateCameraInputsManager(camera) {
  44993. return _super.call(this, camera) || this;
  44994. }
  44995. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44996. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44997. return this;
  44998. };
  44999. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  45000. this.add(new BABYLON.ArcRotateCameraPointersInput());
  45001. return this;
  45002. };
  45003. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  45004. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  45005. return this;
  45006. };
  45007. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  45008. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  45009. return this;
  45010. };
  45011. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  45012. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  45013. return this;
  45014. };
  45015. return ArcRotateCameraInputsManager;
  45016. }(BABYLON.CameraInputsManager));
  45017. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  45018. })(BABYLON || (BABYLON = {}));
  45019. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45020. "use strict";
  45021. var BABYLON;
  45022. (function (BABYLON) {
  45023. var ArcRotateCamera = /** @class */ (function (_super) {
  45024. __extends(ArcRotateCamera, _super);
  45025. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45026. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45027. _this.inertialAlphaOffset = 0;
  45028. _this.inertialBetaOffset = 0;
  45029. _this.inertialRadiusOffset = 0;
  45030. _this.lowerAlphaLimit = null;
  45031. _this.upperAlphaLimit = null;
  45032. _this.lowerBetaLimit = 0.01;
  45033. _this.upperBetaLimit = Math.PI;
  45034. _this.lowerRadiusLimit = null;
  45035. _this.upperRadiusLimit = null;
  45036. _this.inertialPanningX = 0;
  45037. _this.inertialPanningY = 0;
  45038. _this.pinchToPanMaxDistance = 20;
  45039. _this.panningDistanceLimit = null;
  45040. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45041. _this.panningInertia = 0.9;
  45042. //-- end properties for backward compatibility for inputs
  45043. _this.zoomOnFactor = 1;
  45044. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45045. _this.allowUpsideDown = true;
  45046. _this._viewMatrix = new BABYLON.Matrix();
  45047. // Panning
  45048. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45049. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45050. _this.checkCollisions = false;
  45051. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45052. _this._previousPosition = BABYLON.Vector3.Zero();
  45053. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45054. _this._newPosition = BABYLON.Vector3.Zero();
  45055. _this._computationVector = BABYLON.Vector3.Zero();
  45056. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45057. if (collidedMesh === void 0) { collidedMesh = null; }
  45058. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45059. newPosition.multiplyInPlace(_this._collider._radius);
  45060. }
  45061. if (!collidedMesh) {
  45062. _this._previousPosition.copyFrom(_this.position);
  45063. }
  45064. else {
  45065. _this.setPosition(newPosition);
  45066. if (_this.onCollide) {
  45067. _this.onCollide(collidedMesh);
  45068. }
  45069. }
  45070. // Recompute because of constraints
  45071. var cosa = Math.cos(_this.alpha);
  45072. var sina = Math.sin(_this.alpha);
  45073. var cosb = Math.cos(_this.beta);
  45074. var sinb = Math.sin(_this.beta);
  45075. if (sinb === 0) {
  45076. sinb = 0.0001;
  45077. }
  45078. var target = _this._getTargetPosition();
  45079. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45080. target.addToRef(_this._computationVector, _this._newPosition);
  45081. _this.position.copyFrom(_this._newPosition);
  45082. var up = _this.upVector;
  45083. if (_this.allowUpsideDown && _this.beta < 0) {
  45084. up = up.clone();
  45085. up = up.negate();
  45086. }
  45087. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45088. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45089. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45090. _this._collisionTriggered = false;
  45091. };
  45092. _this._target = BABYLON.Vector3.Zero();
  45093. if (target) {
  45094. _this.setTarget(target);
  45095. }
  45096. _this.alpha = alpha;
  45097. _this.beta = beta;
  45098. _this.radius = radius;
  45099. _this.getViewMatrix();
  45100. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45101. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45102. return _this;
  45103. }
  45104. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45105. get: function () {
  45106. return this._target;
  45107. },
  45108. set: function (value) {
  45109. this.setTarget(value);
  45110. },
  45111. enumerable: true,
  45112. configurable: true
  45113. });
  45114. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45115. //-- begin properties for backward compatibility for inputs
  45116. get: function () {
  45117. var pointers = this.inputs.attached["pointers"];
  45118. if (pointers)
  45119. return pointers.angularSensibilityX;
  45120. return 0;
  45121. },
  45122. set: function (value) {
  45123. var pointers = this.inputs.attached["pointers"];
  45124. if (pointers) {
  45125. pointers.angularSensibilityX = value;
  45126. }
  45127. },
  45128. enumerable: true,
  45129. configurable: true
  45130. });
  45131. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45132. get: function () {
  45133. var pointers = this.inputs.attached["pointers"];
  45134. if (pointers)
  45135. return pointers.angularSensibilityY;
  45136. return 0;
  45137. },
  45138. set: function (value) {
  45139. var pointers = this.inputs.attached["pointers"];
  45140. if (pointers) {
  45141. pointers.angularSensibilityY = value;
  45142. }
  45143. },
  45144. enumerable: true,
  45145. configurable: true
  45146. });
  45147. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45148. get: function () {
  45149. var pointers = this.inputs.attached["pointers"];
  45150. if (pointers)
  45151. return pointers.pinchPrecision;
  45152. return 0;
  45153. },
  45154. set: function (value) {
  45155. var pointers = this.inputs.attached["pointers"];
  45156. if (pointers) {
  45157. pointers.pinchPrecision = value;
  45158. }
  45159. },
  45160. enumerable: true,
  45161. configurable: true
  45162. });
  45163. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45164. get: function () {
  45165. var pointers = this.inputs.attached["pointers"];
  45166. if (pointers)
  45167. return pointers.pinchDeltaPercentage;
  45168. return 0;
  45169. },
  45170. set: function (value) {
  45171. var pointers = this.inputs.attached["pointers"];
  45172. if (pointers) {
  45173. pointers.pinchDeltaPercentage = value;
  45174. }
  45175. },
  45176. enumerable: true,
  45177. configurable: true
  45178. });
  45179. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45180. get: function () {
  45181. var pointers = this.inputs.attached["pointers"];
  45182. if (pointers)
  45183. return pointers.panningSensibility;
  45184. return 0;
  45185. },
  45186. set: function (value) {
  45187. var pointers = this.inputs.attached["pointers"];
  45188. if (pointers) {
  45189. pointers.panningSensibility = value;
  45190. }
  45191. },
  45192. enumerable: true,
  45193. configurable: true
  45194. });
  45195. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45196. get: function () {
  45197. var keyboard = this.inputs.attached["keyboard"];
  45198. if (keyboard)
  45199. return keyboard.keysUp;
  45200. return [];
  45201. },
  45202. set: function (value) {
  45203. var keyboard = this.inputs.attached["keyboard"];
  45204. if (keyboard)
  45205. keyboard.keysUp = value;
  45206. },
  45207. enumerable: true,
  45208. configurable: true
  45209. });
  45210. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45211. get: function () {
  45212. var keyboard = this.inputs.attached["keyboard"];
  45213. if (keyboard)
  45214. return keyboard.keysDown;
  45215. return [];
  45216. },
  45217. set: function (value) {
  45218. var keyboard = this.inputs.attached["keyboard"];
  45219. if (keyboard)
  45220. keyboard.keysDown = value;
  45221. },
  45222. enumerable: true,
  45223. configurable: true
  45224. });
  45225. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45226. get: function () {
  45227. var keyboard = this.inputs.attached["keyboard"];
  45228. if (keyboard)
  45229. return keyboard.keysLeft;
  45230. return [];
  45231. },
  45232. set: function (value) {
  45233. var keyboard = this.inputs.attached["keyboard"];
  45234. if (keyboard)
  45235. keyboard.keysLeft = value;
  45236. },
  45237. enumerable: true,
  45238. configurable: true
  45239. });
  45240. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45241. get: function () {
  45242. var keyboard = this.inputs.attached["keyboard"];
  45243. if (keyboard)
  45244. return keyboard.keysRight;
  45245. return [];
  45246. },
  45247. set: function (value) {
  45248. var keyboard = this.inputs.attached["keyboard"];
  45249. if (keyboard)
  45250. keyboard.keysRight = value;
  45251. },
  45252. enumerable: true,
  45253. configurable: true
  45254. });
  45255. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45256. get: function () {
  45257. var mousewheel = this.inputs.attached["mousewheel"];
  45258. if (mousewheel)
  45259. return mousewheel.wheelPrecision;
  45260. return 0;
  45261. },
  45262. set: function (value) {
  45263. var mousewheel = this.inputs.attached["mousewheel"];
  45264. if (mousewheel)
  45265. mousewheel.wheelPrecision = value;
  45266. },
  45267. enumerable: true,
  45268. configurable: true
  45269. });
  45270. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45271. get: function () {
  45272. var mousewheel = this.inputs.attached["mousewheel"];
  45273. if (mousewheel)
  45274. return mousewheel.wheelDeltaPercentage;
  45275. return 0;
  45276. },
  45277. set: function (value) {
  45278. var mousewheel = this.inputs.attached["mousewheel"];
  45279. if (mousewheel)
  45280. mousewheel.wheelDeltaPercentage = value;
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45286. get: function () {
  45287. return this._bouncingBehavior;
  45288. },
  45289. enumerable: true,
  45290. configurable: true
  45291. });
  45292. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45293. get: function () {
  45294. return this._bouncingBehavior != null;
  45295. },
  45296. set: function (value) {
  45297. if (value === this.useBouncingBehavior) {
  45298. return;
  45299. }
  45300. if (value) {
  45301. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45302. this.addBehavior(this._bouncingBehavior);
  45303. }
  45304. else if (this._bouncingBehavior) {
  45305. this.removeBehavior(this._bouncingBehavior);
  45306. this._bouncingBehavior = null;
  45307. }
  45308. },
  45309. enumerable: true,
  45310. configurable: true
  45311. });
  45312. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45313. get: function () {
  45314. return this._framingBehavior;
  45315. },
  45316. enumerable: true,
  45317. configurable: true
  45318. });
  45319. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45320. get: function () {
  45321. return this._framingBehavior != null;
  45322. },
  45323. set: function (value) {
  45324. if (value === this.useFramingBehavior) {
  45325. return;
  45326. }
  45327. if (value) {
  45328. this._framingBehavior = new BABYLON.FramingBehavior();
  45329. this.addBehavior(this._framingBehavior);
  45330. }
  45331. else if (this._framingBehavior) {
  45332. this.removeBehavior(this._framingBehavior);
  45333. this._framingBehavior = null;
  45334. }
  45335. },
  45336. enumerable: true,
  45337. configurable: true
  45338. });
  45339. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45340. get: function () {
  45341. return this._autoRotationBehavior;
  45342. },
  45343. enumerable: true,
  45344. configurable: true
  45345. });
  45346. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45347. get: function () {
  45348. return this._autoRotationBehavior != null;
  45349. },
  45350. set: function (value) {
  45351. if (value === this.useAutoRotationBehavior) {
  45352. return;
  45353. }
  45354. if (value) {
  45355. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45356. this.addBehavior(this._autoRotationBehavior);
  45357. }
  45358. else if (this._autoRotationBehavior) {
  45359. this.removeBehavior(this._autoRotationBehavior);
  45360. this._autoRotationBehavior = null;
  45361. }
  45362. },
  45363. enumerable: true,
  45364. configurable: true
  45365. });
  45366. // Cache
  45367. ArcRotateCamera.prototype._initCache = function () {
  45368. _super.prototype._initCache.call(this);
  45369. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45370. this._cache.alpha = undefined;
  45371. this._cache.beta = undefined;
  45372. this._cache.radius = undefined;
  45373. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45374. };
  45375. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45376. if (!ignoreParentClass) {
  45377. _super.prototype._updateCache.call(this);
  45378. }
  45379. this._cache._target.copyFrom(this._getTargetPosition());
  45380. this._cache.alpha = this.alpha;
  45381. this._cache.beta = this.beta;
  45382. this._cache.radius = this.radius;
  45383. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45384. };
  45385. ArcRotateCamera.prototype._getTargetPosition = function () {
  45386. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45387. var pos = this._targetHost.getAbsolutePosition();
  45388. if (this._targetBoundingCenter) {
  45389. pos.addToRef(this._targetBoundingCenter, this._target);
  45390. }
  45391. else {
  45392. this._target.copyFrom(pos);
  45393. }
  45394. }
  45395. var lockedTargetPosition = this._getLockedTargetPosition();
  45396. if (lockedTargetPosition) {
  45397. return lockedTargetPosition;
  45398. }
  45399. return this._target;
  45400. };
  45401. ArcRotateCamera.prototype.storeState = function () {
  45402. this._storedAlpha = this.alpha;
  45403. this._storedBeta = this.beta;
  45404. this._storedRadius = this.radius;
  45405. this._storedTarget = this._getTargetPosition().clone();
  45406. return _super.prototype.storeState.call(this);
  45407. };
  45408. /**
  45409. * Restored camera state. You must call storeState() first
  45410. */
  45411. ArcRotateCamera.prototype._restoreStateValues = function () {
  45412. if (!_super.prototype._restoreStateValues.call(this)) {
  45413. return false;
  45414. }
  45415. this.alpha = this._storedAlpha;
  45416. this.beta = this._storedBeta;
  45417. this.radius = this._storedRadius;
  45418. this.setTarget(this._storedTarget.clone());
  45419. this.inertialAlphaOffset = 0;
  45420. this.inertialBetaOffset = 0;
  45421. this.inertialRadiusOffset = 0;
  45422. this.inertialPanningX = 0;
  45423. this.inertialPanningY = 0;
  45424. return true;
  45425. };
  45426. // Synchronized
  45427. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45428. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45429. return false;
  45430. return this._cache._target.equals(this._getTargetPosition())
  45431. && this._cache.alpha === this.alpha
  45432. && this._cache.beta === this.beta
  45433. && this._cache.radius === this.radius
  45434. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45435. };
  45436. // Methods
  45437. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45438. var _this = this;
  45439. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45440. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45441. this._useCtrlForPanning = useCtrlForPanning;
  45442. this._panningMouseButton = panningMouseButton;
  45443. this.inputs.attachElement(element, noPreventDefault);
  45444. this._reset = function () {
  45445. _this.inertialAlphaOffset = 0;
  45446. _this.inertialBetaOffset = 0;
  45447. _this.inertialRadiusOffset = 0;
  45448. _this.inertialPanningX = 0;
  45449. _this.inertialPanningY = 0;
  45450. };
  45451. };
  45452. ArcRotateCamera.prototype.detachControl = function (element) {
  45453. this.inputs.detachElement(element);
  45454. if (this._reset) {
  45455. this._reset();
  45456. }
  45457. };
  45458. ArcRotateCamera.prototype._checkInputs = function () {
  45459. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45460. if (this._collisionTriggered) {
  45461. return;
  45462. }
  45463. this.inputs.checkInputs();
  45464. // Inertia
  45465. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45466. if (this.getScene().useRightHandedSystem) {
  45467. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45468. }
  45469. else {
  45470. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45471. }
  45472. this.beta += this.inertialBetaOffset;
  45473. this.radius -= this.inertialRadiusOffset;
  45474. this.inertialAlphaOffset *= this.inertia;
  45475. this.inertialBetaOffset *= this.inertia;
  45476. this.inertialRadiusOffset *= this.inertia;
  45477. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45478. this.inertialAlphaOffset = 0;
  45479. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45480. this.inertialBetaOffset = 0;
  45481. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45482. this.inertialRadiusOffset = 0;
  45483. }
  45484. // Panning inertia
  45485. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45486. if (!this._localDirection) {
  45487. this._localDirection = BABYLON.Vector3.Zero();
  45488. this._transformedDirection = BABYLON.Vector3.Zero();
  45489. }
  45490. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45491. this._localDirection.multiplyInPlace(this.panningAxis);
  45492. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45493. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45494. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45495. if (!this.panningAxis.y) {
  45496. this._transformedDirection.y = 0;
  45497. }
  45498. if (!this._targetHost) {
  45499. if (this.panningDistanceLimit) {
  45500. this._transformedDirection.addInPlace(this._target);
  45501. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45502. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45503. this._target.copyFrom(this._transformedDirection);
  45504. }
  45505. }
  45506. else {
  45507. this._target.addInPlace(this._transformedDirection);
  45508. }
  45509. }
  45510. this.inertialPanningX *= this.panningInertia;
  45511. this.inertialPanningY *= this.panningInertia;
  45512. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45513. this.inertialPanningX = 0;
  45514. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45515. this.inertialPanningY = 0;
  45516. }
  45517. // Limits
  45518. this._checkLimits();
  45519. _super.prototype._checkInputs.call(this);
  45520. };
  45521. ArcRotateCamera.prototype._checkLimits = function () {
  45522. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45523. if (this.allowUpsideDown && this.beta > Math.PI) {
  45524. this.beta = this.beta - (2 * Math.PI);
  45525. }
  45526. }
  45527. else {
  45528. if (this.beta < this.lowerBetaLimit) {
  45529. this.beta = this.lowerBetaLimit;
  45530. }
  45531. }
  45532. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45533. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45534. this.beta = this.beta + (2 * Math.PI);
  45535. }
  45536. }
  45537. else {
  45538. if (this.beta > this.upperBetaLimit) {
  45539. this.beta = this.upperBetaLimit;
  45540. }
  45541. }
  45542. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45543. this.alpha = this.lowerAlphaLimit;
  45544. }
  45545. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45546. this.alpha = this.upperAlphaLimit;
  45547. }
  45548. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45549. this.radius = this.lowerRadiusLimit;
  45550. }
  45551. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45552. this.radius = this.upperRadiusLimit;
  45553. }
  45554. };
  45555. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45556. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45557. this.radius = this._computationVector.length();
  45558. if (this.radius === 0) {
  45559. this.radius = 0.0001; // Just to avoid division by zero
  45560. }
  45561. // Alpha
  45562. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45563. if (this._computationVector.z < 0) {
  45564. this.alpha = 2 * Math.PI - this.alpha;
  45565. }
  45566. // Beta
  45567. this.beta = Math.acos(this._computationVector.y / this.radius);
  45568. this._checkLimits();
  45569. };
  45570. ArcRotateCamera.prototype.setPosition = function (position) {
  45571. if (this.position.equals(position)) {
  45572. return;
  45573. }
  45574. this.position.copyFrom(position);
  45575. this.rebuildAnglesAndRadius();
  45576. };
  45577. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45578. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45579. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45580. if (target.getBoundingInfo) {
  45581. if (toBoundingCenter) {
  45582. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45583. }
  45584. else {
  45585. this._targetBoundingCenter = null;
  45586. }
  45587. this._targetHost = target;
  45588. this._target = this._getTargetPosition();
  45589. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45590. }
  45591. else {
  45592. var newTarget = target;
  45593. var currentTarget = this._getTargetPosition();
  45594. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45595. return;
  45596. }
  45597. this._targetHost = null;
  45598. this._target = newTarget;
  45599. this._targetBoundingCenter = null;
  45600. this.onMeshTargetChangedObservable.notifyObservers(null);
  45601. }
  45602. this.rebuildAnglesAndRadius();
  45603. };
  45604. ArcRotateCamera.prototype._getViewMatrix = function () {
  45605. // Compute
  45606. var cosa = Math.cos(this.alpha);
  45607. var sina = Math.sin(this.alpha);
  45608. var cosb = Math.cos(this.beta);
  45609. var sinb = Math.sin(this.beta);
  45610. if (sinb === 0) {
  45611. sinb = 0.0001;
  45612. }
  45613. var target = this._getTargetPosition();
  45614. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45615. target.addToRef(this._computationVector, this._newPosition);
  45616. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45617. if (!this._collider) {
  45618. this._collider = new BABYLON.Collider();
  45619. }
  45620. this._collider._radius = this.collisionRadius;
  45621. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45622. this._collisionTriggered = true;
  45623. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45624. }
  45625. else {
  45626. this.position.copyFrom(this._newPosition);
  45627. var up = this.upVector;
  45628. if (this.allowUpsideDown && sinb < 0) {
  45629. up = up.clone();
  45630. up = up.negate();
  45631. }
  45632. if (this.getScene().useRightHandedSystem) {
  45633. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45634. }
  45635. else {
  45636. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45637. }
  45638. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45639. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45640. }
  45641. this._currentTarget = target;
  45642. return this._viewMatrix;
  45643. };
  45644. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45645. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45646. meshes = meshes || this.getScene().meshes;
  45647. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45648. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45649. this.radius = distance * this.zoomOnFactor;
  45650. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45651. };
  45652. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45653. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45654. var meshesOrMinMaxVector;
  45655. var distance;
  45656. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45657. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45658. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45659. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45660. }
  45661. else {
  45662. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45663. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45664. distance = minMaxVectorAndDistance.distance;
  45665. }
  45666. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45667. if (!doNotUpdateMaxZ) {
  45668. this.maxZ = distance * 2;
  45669. }
  45670. };
  45671. /**
  45672. * @override
  45673. * Override Camera.createRigCamera
  45674. */
  45675. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45676. var alphaShift = 0;
  45677. switch (this.cameraRigMode) {
  45678. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45679. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45680. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45681. case BABYLON.Camera.RIG_MODE_VR:
  45682. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45683. break;
  45684. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45685. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45686. break;
  45687. }
  45688. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45689. rigCam._cameraRigParams = {};
  45690. return rigCam;
  45691. };
  45692. /**
  45693. * @override
  45694. * Override Camera._updateRigCameras
  45695. */
  45696. ArcRotateCamera.prototype._updateRigCameras = function () {
  45697. var camLeft = this._rigCameras[0];
  45698. var camRight = this._rigCameras[1];
  45699. camLeft.beta = camRight.beta = this.beta;
  45700. camLeft.radius = camRight.radius = this.radius;
  45701. switch (this.cameraRigMode) {
  45702. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45703. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45704. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45705. case BABYLON.Camera.RIG_MODE_VR:
  45706. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45707. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45708. break;
  45709. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45710. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45711. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45712. break;
  45713. }
  45714. _super.prototype._updateRigCameras.call(this);
  45715. };
  45716. ArcRotateCamera.prototype.dispose = function () {
  45717. this.inputs.clear();
  45718. _super.prototype.dispose.call(this);
  45719. };
  45720. ArcRotateCamera.prototype.getClassName = function () {
  45721. return "ArcRotateCamera";
  45722. };
  45723. __decorate([
  45724. BABYLON.serialize()
  45725. ], ArcRotateCamera.prototype, "alpha", void 0);
  45726. __decorate([
  45727. BABYLON.serialize()
  45728. ], ArcRotateCamera.prototype, "beta", void 0);
  45729. __decorate([
  45730. BABYLON.serialize()
  45731. ], ArcRotateCamera.prototype, "radius", void 0);
  45732. __decorate([
  45733. BABYLON.serializeAsVector3("target")
  45734. ], ArcRotateCamera.prototype, "_target", void 0);
  45735. __decorate([
  45736. BABYLON.serialize()
  45737. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45738. __decorate([
  45739. BABYLON.serialize()
  45740. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45741. __decorate([
  45742. BABYLON.serialize()
  45743. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45744. __decorate([
  45745. BABYLON.serialize()
  45746. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45747. __decorate([
  45748. BABYLON.serialize()
  45749. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45750. __decorate([
  45751. BABYLON.serialize()
  45752. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45753. __decorate([
  45754. BABYLON.serialize()
  45755. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45756. __decorate([
  45757. BABYLON.serialize()
  45758. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45759. __decorate([
  45760. BABYLON.serialize()
  45761. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45762. __decorate([
  45763. BABYLON.serialize()
  45764. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45765. __decorate([
  45766. BABYLON.serialize()
  45767. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45768. __decorate([
  45769. BABYLON.serialize()
  45770. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45771. __decorate([
  45772. BABYLON.serialize()
  45773. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45774. __decorate([
  45775. BABYLON.serializeAsVector3()
  45776. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45777. __decorate([
  45778. BABYLON.serialize()
  45779. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45780. __decorate([
  45781. BABYLON.serialize()
  45782. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45783. __decorate([
  45784. BABYLON.serialize()
  45785. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45786. return ArcRotateCamera;
  45787. }(BABYLON.TargetCamera));
  45788. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45789. })(BABYLON || (BABYLON = {}));
  45790. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45791. "use strict";
  45792. var BABYLON;
  45793. (function (BABYLON) {
  45794. /**
  45795. * The HemisphericLight simulates the ambient environment light,
  45796. * so the passed direction is the light reflection direction, not the incoming direction.
  45797. */
  45798. var HemisphericLight = /** @class */ (function (_super) {
  45799. __extends(HemisphericLight, _super);
  45800. /**
  45801. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45802. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45803. * The HemisphericLight can't cast shadows.
  45804. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45805. * @param name The friendly name of the light
  45806. * @param direction The direction of the light reflection
  45807. * @param scene The scene the light belongs to
  45808. */
  45809. function HemisphericLight(name, direction, scene) {
  45810. var _this = _super.call(this, name, scene) || this;
  45811. /**
  45812. * The groundColor is the light in the opposite direction to the one specified during creation.
  45813. * 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.
  45814. */
  45815. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45816. _this.direction = direction || BABYLON.Vector3.Up();
  45817. return _this;
  45818. }
  45819. HemisphericLight.prototype._buildUniformLayout = function () {
  45820. this._uniformBuffer.addUniform("vLightData", 4);
  45821. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45822. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45823. this._uniformBuffer.addUniform("vLightGround", 3);
  45824. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45825. this._uniformBuffer.addUniform("depthValues", 2);
  45826. this._uniformBuffer.create();
  45827. };
  45828. /**
  45829. * Returns the string "HemisphericLight".
  45830. * @return The class name
  45831. */
  45832. HemisphericLight.prototype.getClassName = function () {
  45833. return "HemisphericLight";
  45834. };
  45835. /**
  45836. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45837. * Returns the updated direction.
  45838. * @param target The target the direction should point to
  45839. * @return The computed direction
  45840. */
  45841. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45842. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45843. return this.direction;
  45844. };
  45845. /**
  45846. * Returns the shadow generator associated to the light.
  45847. * @returns Always null for hemispheric lights because it does not support shadows.
  45848. */
  45849. HemisphericLight.prototype.getShadowGenerator = function () {
  45850. return null;
  45851. };
  45852. /**
  45853. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45854. * @param effect The effect to update
  45855. * @param lightIndex The index of the light in the effect to update
  45856. * @returns The hemispheric light
  45857. */
  45858. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45859. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45860. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45861. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45862. return this;
  45863. };
  45864. /**
  45865. * @ignore internal use only.
  45866. */
  45867. HemisphericLight.prototype._getWorldMatrix = function () {
  45868. if (!this._worldMatrix) {
  45869. this._worldMatrix = BABYLON.Matrix.Identity();
  45870. }
  45871. return this._worldMatrix;
  45872. };
  45873. /**
  45874. * Returns the integer 3.
  45875. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45876. */
  45877. HemisphericLight.prototype.getTypeID = function () {
  45878. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45879. };
  45880. __decorate([
  45881. BABYLON.serializeAsColor3()
  45882. ], HemisphericLight.prototype, "groundColor", void 0);
  45883. __decorate([
  45884. BABYLON.serializeAsVector3()
  45885. ], HemisphericLight.prototype, "direction", void 0);
  45886. return HemisphericLight;
  45887. }(BABYLON.Light));
  45888. BABYLON.HemisphericLight = HemisphericLight;
  45889. })(BABYLON || (BABYLON = {}));
  45890. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45891. "use strict";
  45892. var BABYLON;
  45893. (function (BABYLON) {
  45894. /**
  45895. * Base implementation of @see IShadowLight
  45896. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45897. */
  45898. var ShadowLight = /** @class */ (function (_super) {
  45899. __extends(ShadowLight, _super);
  45900. function ShadowLight() {
  45901. var _this = _super !== null && _super.apply(this, arguments) || this;
  45902. _this._needProjectionMatrixCompute = true;
  45903. return _this;
  45904. }
  45905. ShadowLight.prototype._setPosition = function (value) {
  45906. this._position = value;
  45907. };
  45908. Object.defineProperty(ShadowLight.prototype, "position", {
  45909. /**
  45910. * Sets the position the shadow will be casted from. Also use as the light position for both
  45911. * point and spot lights.
  45912. */
  45913. get: function () {
  45914. return this._position;
  45915. },
  45916. /**
  45917. * Sets the position the shadow will be casted from. Also use as the light position for both
  45918. * point and spot lights.
  45919. */
  45920. set: function (value) {
  45921. this._setPosition(value);
  45922. },
  45923. enumerable: true,
  45924. configurable: true
  45925. });
  45926. ShadowLight.prototype._setDirection = function (value) {
  45927. this._direction = value;
  45928. };
  45929. Object.defineProperty(ShadowLight.prototype, "direction", {
  45930. /**
  45931. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45932. * Also use as the light direction on spot and directional lights.
  45933. */
  45934. get: function () {
  45935. return this._direction;
  45936. },
  45937. /**
  45938. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45939. * Also use as the light direction on spot and directional lights.
  45940. */
  45941. set: function (value) {
  45942. this._setDirection(value);
  45943. },
  45944. enumerable: true,
  45945. configurable: true
  45946. });
  45947. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45948. /**
  45949. * Gets the shadow projection clipping minimum z value.
  45950. */
  45951. get: function () {
  45952. return this._shadowMinZ;
  45953. },
  45954. /**
  45955. * Sets the shadow projection clipping minimum z value.
  45956. */
  45957. set: function (value) {
  45958. this._shadowMinZ = value;
  45959. this.forceProjectionMatrixCompute();
  45960. },
  45961. enumerable: true,
  45962. configurable: true
  45963. });
  45964. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45965. /**
  45966. * Sets the shadow projection clipping maximum z value.
  45967. */
  45968. get: function () {
  45969. return this._shadowMaxZ;
  45970. },
  45971. /**
  45972. * Gets the shadow projection clipping maximum z value.
  45973. */
  45974. set: function (value) {
  45975. this._shadowMaxZ = value;
  45976. this.forceProjectionMatrixCompute();
  45977. },
  45978. enumerable: true,
  45979. configurable: true
  45980. });
  45981. /**
  45982. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45983. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45984. */
  45985. ShadowLight.prototype.computeTransformedInformation = function () {
  45986. if (this.parent && this.parent.getWorldMatrix) {
  45987. if (!this.transformedPosition) {
  45988. this.transformedPosition = BABYLON.Vector3.Zero();
  45989. }
  45990. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45991. // In case the direction is present.
  45992. if (this.direction) {
  45993. if (!this.transformedDirection) {
  45994. this.transformedDirection = BABYLON.Vector3.Zero();
  45995. }
  45996. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45997. }
  45998. return true;
  45999. }
  46000. return false;
  46001. };
  46002. /**
  46003. * Return the depth scale used for the shadow map.
  46004. * @returns the depth scale.
  46005. */
  46006. ShadowLight.prototype.getDepthScale = function () {
  46007. return 50.0;
  46008. };
  46009. /**
  46010. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  46011. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46012. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46013. */
  46014. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  46015. return this.transformedDirection ? this.transformedDirection : this.direction;
  46016. };
  46017. /**
  46018. * Returns the ShadowLight absolute position in the World.
  46019. * @returns the position vector in world space
  46020. */
  46021. ShadowLight.prototype.getAbsolutePosition = function () {
  46022. return this.transformedPosition ? this.transformedPosition : this.position;
  46023. };
  46024. /**
  46025. * Sets the ShadowLight direction toward the passed target.
  46026. * @param target The point tot target in local space
  46027. * @returns the updated ShadowLight direction
  46028. */
  46029. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46030. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46031. return this.direction;
  46032. };
  46033. /**
  46034. * Returns the light rotation in euler definition.
  46035. * @returns the x y z rotation in local space.
  46036. */
  46037. ShadowLight.prototype.getRotation = function () {
  46038. this.direction.normalize();
  46039. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46040. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46041. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46042. };
  46043. /**
  46044. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46045. * @returns true if a cube texture needs to be use
  46046. */
  46047. ShadowLight.prototype.needCube = function () {
  46048. return false;
  46049. };
  46050. /**
  46051. * Detects if the projection matrix requires to be recomputed this frame.
  46052. * @returns true if it requires to be recomputed otherwise, false.
  46053. */
  46054. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46055. return this._needProjectionMatrixCompute;
  46056. };
  46057. /**
  46058. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46059. */
  46060. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46061. this._needProjectionMatrixCompute = true;
  46062. };
  46063. /**
  46064. * Get the world matrix of the sahdow lights.
  46065. * @ignore Internal Use Only
  46066. */
  46067. ShadowLight.prototype._getWorldMatrix = function () {
  46068. if (!this._worldMatrix) {
  46069. this._worldMatrix = BABYLON.Matrix.Identity();
  46070. }
  46071. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46072. return this._worldMatrix;
  46073. };
  46074. /**
  46075. * Gets the minZ used for shadow according to both the scene and the light.
  46076. * @param activeCamera The camera we are returning the min for
  46077. * @returns the depth min z
  46078. */
  46079. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46080. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46081. };
  46082. /**
  46083. * Gets the maxZ used for shadow according to both the scene and the light.
  46084. * @param activeCamera The camera we are returning the max for
  46085. * @returns the depth max z
  46086. */
  46087. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46088. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46089. };
  46090. /**
  46091. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46092. * @param matrix The materix to updated with the projection information
  46093. * @param viewMatrix The transform matrix of the light
  46094. * @param renderList The list of mesh to render in the map
  46095. * @returns The current light
  46096. */
  46097. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46098. if (this.customProjectionMatrixBuilder) {
  46099. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46100. }
  46101. else {
  46102. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46103. }
  46104. return this;
  46105. };
  46106. __decorate([
  46107. BABYLON.serializeAsVector3()
  46108. ], ShadowLight.prototype, "position", null);
  46109. __decorate([
  46110. BABYLON.serializeAsVector3()
  46111. ], ShadowLight.prototype, "direction", null);
  46112. __decorate([
  46113. BABYLON.serialize()
  46114. ], ShadowLight.prototype, "shadowMinZ", null);
  46115. __decorate([
  46116. BABYLON.serialize()
  46117. ], ShadowLight.prototype, "shadowMaxZ", null);
  46118. return ShadowLight;
  46119. }(BABYLON.Light));
  46120. BABYLON.ShadowLight = ShadowLight;
  46121. })(BABYLON || (BABYLON = {}));
  46122. //# sourceMappingURL=babylon.shadowLight.js.map
  46123. "use strict";
  46124. var BABYLON;
  46125. (function (BABYLON) {
  46126. /**
  46127. * A point light is a light defined by an unique point in world space.
  46128. * The light is emitted in every direction from this point.
  46129. * A good example of a point light is a standard light bulb.
  46130. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46131. */
  46132. var PointLight = /** @class */ (function (_super) {
  46133. __extends(PointLight, _super);
  46134. /**
  46135. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46136. * A PointLight emits the light in every direction.
  46137. * It can cast shadows.
  46138. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46139. * ```javascript
  46140. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46141. * ```
  46142. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46143. * @param name The light friendly name
  46144. * @param position The position of the point light in the scene
  46145. * @param scene The scene the lights belongs to
  46146. */
  46147. function PointLight(name, position, scene) {
  46148. var _this = _super.call(this, name, scene) || this;
  46149. _this._shadowAngle = Math.PI / 2;
  46150. _this.position = position;
  46151. return _this;
  46152. }
  46153. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46154. /**
  46155. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46156. * This specifies what angle the shadow will use to be created.
  46157. *
  46158. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46159. */
  46160. get: function () {
  46161. return this._shadowAngle;
  46162. },
  46163. /**
  46164. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46165. * This specifies what angle the shadow will use to be created.
  46166. *
  46167. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46168. */
  46169. set: function (value) {
  46170. this._shadowAngle = value;
  46171. this.forceProjectionMatrixCompute();
  46172. },
  46173. enumerable: true,
  46174. configurable: true
  46175. });
  46176. Object.defineProperty(PointLight.prototype, "direction", {
  46177. /**
  46178. * Gets the direction if it has been set.
  46179. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46180. */
  46181. get: function () {
  46182. return this._direction;
  46183. },
  46184. /**
  46185. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46186. */
  46187. set: function (value) {
  46188. var previousNeedCube = this.needCube();
  46189. this._direction = value;
  46190. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46191. this._shadowGenerator.recreateShadowMap();
  46192. }
  46193. },
  46194. enumerable: true,
  46195. configurable: true
  46196. });
  46197. /**
  46198. * Returns the string "PointLight"
  46199. * @returns the class name
  46200. */
  46201. PointLight.prototype.getClassName = function () {
  46202. return "PointLight";
  46203. };
  46204. /**
  46205. * Returns the integer 0.
  46206. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46207. */
  46208. PointLight.prototype.getTypeID = function () {
  46209. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46210. };
  46211. /**
  46212. * Specifies wether or not the shadowmap should be a cube texture.
  46213. * @returns true if the shadowmap needs to be a cube texture.
  46214. */
  46215. PointLight.prototype.needCube = function () {
  46216. return !this.direction;
  46217. };
  46218. /**
  46219. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46220. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46221. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46222. */
  46223. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46224. if (this.direction) {
  46225. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46226. }
  46227. else {
  46228. switch (faceIndex) {
  46229. case 0:
  46230. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46231. case 1:
  46232. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46233. case 2:
  46234. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46235. case 3:
  46236. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46237. case 4:
  46238. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46239. case 5:
  46240. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46241. }
  46242. }
  46243. return BABYLON.Vector3.Zero();
  46244. };
  46245. /**
  46246. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46247. * - fov = PI / 2
  46248. * - aspect ratio : 1.0
  46249. * - z-near and far equal to the active camera minZ and maxZ.
  46250. * Returns the PointLight.
  46251. */
  46252. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46253. var activeCamera = this.getScene().activeCamera;
  46254. if (!activeCamera) {
  46255. return;
  46256. }
  46257. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46258. };
  46259. PointLight.prototype._buildUniformLayout = function () {
  46260. this._uniformBuffer.addUniform("vLightData", 4);
  46261. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46262. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46263. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46264. this._uniformBuffer.addUniform("depthValues", 2);
  46265. this._uniformBuffer.create();
  46266. };
  46267. /**
  46268. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46269. * @param effect The effect to update
  46270. * @param lightIndex The index of the light in the effect to update
  46271. * @returns The point light
  46272. */
  46273. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46274. if (this.computeTransformedInformation()) {
  46275. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46276. return this;
  46277. }
  46278. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46279. return this;
  46280. };
  46281. __decorate([
  46282. BABYLON.serialize()
  46283. ], PointLight.prototype, "shadowAngle", null);
  46284. return PointLight;
  46285. }(BABYLON.ShadowLight));
  46286. BABYLON.PointLight = PointLight;
  46287. })(BABYLON || (BABYLON = {}));
  46288. //# sourceMappingURL=babylon.pointLight.js.map
  46289. "use strict";
  46290. var BABYLON;
  46291. (function (BABYLON) {
  46292. /**
  46293. * A directional light is defined by a direction (what a surprise!).
  46294. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46295. * 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.
  46296. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46297. */
  46298. var DirectionalLight = /** @class */ (function (_super) {
  46299. __extends(DirectionalLight, _super);
  46300. /**
  46301. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46302. * The directional light is emitted from everywhere in the given direction.
  46303. * It can cast shawdows.
  46304. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46305. * @param name The friendly name of the light
  46306. * @param direction The direction of the light
  46307. * @param scene The scene the light belongs to
  46308. */
  46309. function DirectionalLight(name, direction, scene) {
  46310. var _this = _super.call(this, name, scene) || this;
  46311. _this._shadowFrustumSize = 0;
  46312. _this._shadowOrthoScale = 0.1;
  46313. /**
  46314. * Automatically compute the projection matrix to best fit (including all the casters)
  46315. * on each frame.
  46316. */
  46317. _this.autoUpdateExtends = true;
  46318. // Cache
  46319. _this._orthoLeft = Number.MAX_VALUE;
  46320. _this._orthoRight = Number.MIN_VALUE;
  46321. _this._orthoTop = Number.MIN_VALUE;
  46322. _this._orthoBottom = Number.MAX_VALUE;
  46323. _this.position = direction.scale(-1.0);
  46324. _this.direction = direction;
  46325. return _this;
  46326. }
  46327. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46328. /**
  46329. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46330. */
  46331. get: function () {
  46332. return this._shadowFrustumSize;
  46333. },
  46334. /**
  46335. * Specifies a fix frustum size for the shadow generation.
  46336. */
  46337. set: function (value) {
  46338. this._shadowFrustumSize = value;
  46339. this.forceProjectionMatrixCompute();
  46340. },
  46341. enumerable: true,
  46342. configurable: true
  46343. });
  46344. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46345. /**
  46346. * Gets the shadow projection scale against the optimal computed one.
  46347. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46348. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46349. */
  46350. get: function () {
  46351. return this._shadowOrthoScale;
  46352. },
  46353. /**
  46354. * Sets the shadow projection scale against the optimal computed one.
  46355. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46356. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46357. */
  46358. set: function (value) {
  46359. this._shadowOrthoScale = value;
  46360. this.forceProjectionMatrixCompute();
  46361. },
  46362. enumerable: true,
  46363. configurable: true
  46364. });
  46365. /**
  46366. * Returns the string "DirectionalLight".
  46367. * @return The class name
  46368. */
  46369. DirectionalLight.prototype.getClassName = function () {
  46370. return "DirectionalLight";
  46371. };
  46372. /**
  46373. * Returns the integer 1.
  46374. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46375. */
  46376. DirectionalLight.prototype.getTypeID = function () {
  46377. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46378. };
  46379. /**
  46380. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46381. * Returns the DirectionalLight Shadow projection matrix.
  46382. */
  46383. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46384. if (this.shadowFrustumSize > 0) {
  46385. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46386. }
  46387. else {
  46388. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46389. }
  46390. };
  46391. /**
  46392. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46393. * Returns the DirectionalLight Shadow projection matrix.
  46394. */
  46395. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46396. var activeCamera = this.getScene().activeCamera;
  46397. if (!activeCamera) {
  46398. return;
  46399. }
  46400. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46401. };
  46402. /**
  46403. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46404. * Returns the DirectionalLight Shadow projection matrix.
  46405. */
  46406. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46407. var activeCamera = this.getScene().activeCamera;
  46408. if (!activeCamera) {
  46409. return;
  46410. }
  46411. // Check extends
  46412. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46413. var tempVector3 = BABYLON.Vector3.Zero();
  46414. this._orthoLeft = Number.MAX_VALUE;
  46415. this._orthoRight = Number.MIN_VALUE;
  46416. this._orthoTop = Number.MIN_VALUE;
  46417. this._orthoBottom = Number.MAX_VALUE;
  46418. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46419. var mesh = renderList[meshIndex];
  46420. if (!mesh) {
  46421. continue;
  46422. }
  46423. var boundingInfo = mesh.getBoundingInfo();
  46424. var boundingBox = boundingInfo.boundingBox;
  46425. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46426. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46427. if (tempVector3.x < this._orthoLeft)
  46428. this._orthoLeft = tempVector3.x;
  46429. if (tempVector3.y < this._orthoBottom)
  46430. this._orthoBottom = tempVector3.y;
  46431. if (tempVector3.x > this._orthoRight)
  46432. this._orthoRight = tempVector3.x;
  46433. if (tempVector3.y > this._orthoTop)
  46434. this._orthoTop = tempVector3.y;
  46435. }
  46436. }
  46437. }
  46438. var xOffset = this._orthoRight - this._orthoLeft;
  46439. var yOffset = this._orthoTop - this._orthoBottom;
  46440. 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);
  46441. };
  46442. DirectionalLight.prototype._buildUniformLayout = function () {
  46443. this._uniformBuffer.addUniform("vLightData", 4);
  46444. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46445. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46446. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46447. this._uniformBuffer.addUniform("depthValues", 2);
  46448. this._uniformBuffer.create();
  46449. };
  46450. /**
  46451. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46452. * @param effect The effect to update
  46453. * @param lightIndex The index of the light in the effect to update
  46454. * @returns The directional light
  46455. */
  46456. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46457. if (this.computeTransformedInformation()) {
  46458. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46459. return this;
  46460. }
  46461. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46462. return this;
  46463. };
  46464. /**
  46465. * Gets the minZ used for shadow according to both the scene and the light.
  46466. *
  46467. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46468. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46469. * @param activeCamera The camera we are returning the min for
  46470. * @returns the depth min z
  46471. */
  46472. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46473. return 1;
  46474. };
  46475. /**
  46476. * Gets the maxZ used for shadow according to both the scene and the light.
  46477. *
  46478. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46479. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46480. * @param activeCamera The camera we are returning the max for
  46481. * @returns the depth max z
  46482. */
  46483. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46484. return 1;
  46485. };
  46486. __decorate([
  46487. BABYLON.serialize()
  46488. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46489. __decorate([
  46490. BABYLON.serialize()
  46491. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46492. __decorate([
  46493. BABYLON.serialize()
  46494. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46495. return DirectionalLight;
  46496. }(BABYLON.ShadowLight));
  46497. BABYLON.DirectionalLight = DirectionalLight;
  46498. })(BABYLON || (BABYLON = {}));
  46499. //# sourceMappingURL=babylon.directionalLight.js.map
  46500. "use strict";
  46501. var BABYLON;
  46502. (function (BABYLON) {
  46503. /**
  46504. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46505. * These values define a cone of light starting from the position, emitting toward the direction.
  46506. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46507. * and the exponent defines the speed of the decay of the light with distance (reach).
  46508. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46509. */
  46510. var SpotLight = /** @class */ (function (_super) {
  46511. __extends(SpotLight, _super);
  46512. /**
  46513. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46514. * It can cast shadows.
  46515. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46516. * @param name The light friendly name
  46517. * @param position The position of the spot light in the scene
  46518. * @param direction The direction of the light in the scene
  46519. * @param angle The cone angle of the light in Radians
  46520. * @param exponent The light decay speed with the distance from the emission spot
  46521. * @param scene The scene the lights belongs to
  46522. */
  46523. function SpotLight(name, position, direction, angle, exponent, scene) {
  46524. var _this = _super.call(this, name, scene) || this;
  46525. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46526. _this._projectionTextureLightNear = 1e-6;
  46527. _this._projectionTextureLightFar = 1000.0;
  46528. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46529. _this._projectionTextureViewLightDirty = true;
  46530. _this._projectionTextureProjectionLightDirty = true;
  46531. _this._projectionTextureDirty = true;
  46532. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46533. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46534. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46535. _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);
  46536. _this.position = position;
  46537. _this.direction = direction;
  46538. _this.angle = angle;
  46539. _this.exponent = exponent;
  46540. return _this;
  46541. }
  46542. Object.defineProperty(SpotLight.prototype, "angle", {
  46543. /**
  46544. * Gets the cone angle of the spot light in Radians.
  46545. */
  46546. get: function () {
  46547. return this._angle;
  46548. },
  46549. /**
  46550. * Sets the cone angle of the spot light in Radians.
  46551. */
  46552. set: function (value) {
  46553. this._angle = value;
  46554. this._projectionTextureProjectionLightDirty = true;
  46555. this.forceProjectionMatrixCompute();
  46556. },
  46557. enumerable: true,
  46558. configurable: true
  46559. });
  46560. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46561. /**
  46562. * Allows scaling the angle of the light for shadow generation only.
  46563. */
  46564. get: function () {
  46565. return this._shadowAngleScale;
  46566. },
  46567. /**
  46568. * Allows scaling the angle of the light for shadow generation only.
  46569. */
  46570. set: function (value) {
  46571. this._shadowAngleScale = value;
  46572. this.forceProjectionMatrixCompute();
  46573. },
  46574. enumerable: true,
  46575. configurable: true
  46576. });
  46577. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46578. /**
  46579. * Allows reading the projecton texture
  46580. */
  46581. get: function () {
  46582. return this._projectionTextureMatrix;
  46583. },
  46584. enumerable: true,
  46585. configurable: true
  46586. });
  46587. ;
  46588. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46589. /**
  46590. * Gets the near clip of the Spotlight for texture projection.
  46591. */
  46592. get: function () {
  46593. return this._projectionTextureLightNear;
  46594. },
  46595. /**
  46596. * Sets the near clip of the Spotlight for texture projection.
  46597. */
  46598. set: function (value) {
  46599. this._projectionTextureLightNear = value;
  46600. this._projectionTextureProjectionLightDirty = true;
  46601. },
  46602. enumerable: true,
  46603. configurable: true
  46604. });
  46605. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46606. /**
  46607. * Gets the far clip of the Spotlight for texture projection.
  46608. */
  46609. get: function () {
  46610. return this._projectionTextureLightFar;
  46611. },
  46612. /**
  46613. * Sets the far clip of the Spotlight for texture projection.
  46614. */
  46615. set: function (value) {
  46616. this._projectionTextureLightFar = value;
  46617. this._projectionTextureProjectionLightDirty = true;
  46618. },
  46619. enumerable: true,
  46620. configurable: true
  46621. });
  46622. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46623. /**
  46624. * Gets the Up vector of the Spotlight for texture projection.
  46625. */
  46626. get: function () {
  46627. return this._projectionTextureUpDirection;
  46628. },
  46629. /**
  46630. * Sets the Up vector of the Spotlight for texture projection.
  46631. */
  46632. set: function (value) {
  46633. this._projectionTextureUpDirection = value;
  46634. this._projectionTextureProjectionLightDirty = true;
  46635. },
  46636. enumerable: true,
  46637. configurable: true
  46638. });
  46639. ;
  46640. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46641. /**
  46642. * Gets the projection texture of the light.
  46643. */
  46644. get: function () {
  46645. return this._projectionTexture;
  46646. },
  46647. /**
  46648. * Sets the projection texture of the light.
  46649. */
  46650. set: function (value) {
  46651. this._projectionTexture = value;
  46652. this._projectionTextureDirty = true;
  46653. },
  46654. enumerable: true,
  46655. configurable: true
  46656. });
  46657. /**
  46658. * Returns the string "SpotLight".
  46659. * @returns the class name
  46660. */
  46661. SpotLight.prototype.getClassName = function () {
  46662. return "SpotLight";
  46663. };
  46664. /**
  46665. * Returns the integer 2.
  46666. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46667. */
  46668. SpotLight.prototype.getTypeID = function () {
  46669. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46670. };
  46671. /**
  46672. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46673. */
  46674. SpotLight.prototype._setDirection = function (value) {
  46675. _super.prototype._setDirection.call(this, value);
  46676. this._projectionTextureViewLightDirty = true;
  46677. };
  46678. /**
  46679. * Overrides the position setter to recompute the projection texture view light Matrix.
  46680. */
  46681. SpotLight.prototype._setPosition = function (value) {
  46682. _super.prototype._setPosition.call(this, value);
  46683. this._projectionTextureViewLightDirty = true;
  46684. };
  46685. /**
  46686. * 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.
  46687. * Returns the SpotLight.
  46688. */
  46689. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46690. var activeCamera = this.getScene().activeCamera;
  46691. if (!activeCamera) {
  46692. return;
  46693. }
  46694. this._shadowAngleScale = this._shadowAngleScale || 1;
  46695. var angle = this._shadowAngleScale * this._angle;
  46696. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46697. };
  46698. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46699. this._projectionTextureViewLightDirty = false;
  46700. this._projectionTextureDirty = true;
  46701. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46702. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46703. };
  46704. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46705. this._projectionTextureProjectionLightDirty = false;
  46706. this._projectionTextureDirty = true;
  46707. var light_far = this.projectionTextureLightFar;
  46708. var light_near = this.projectionTextureLightNear;
  46709. var P = light_far / (light_far - light_near);
  46710. var Q = -P * light_near;
  46711. var S = 1.0 / Math.tan(this._angle / 2.0);
  46712. var A = 1.0;
  46713. 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);
  46714. };
  46715. /**
  46716. * Main function for light texture projection matrix computing.
  46717. */
  46718. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46719. this._projectionTextureDirty = false;
  46720. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46721. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46722. };
  46723. SpotLight.prototype._buildUniformLayout = function () {
  46724. this._uniformBuffer.addUniform("vLightData", 4);
  46725. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46726. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46727. this._uniformBuffer.addUniform("vLightDirection", 3);
  46728. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46729. this._uniformBuffer.addUniform("depthValues", 2);
  46730. this._uniformBuffer.create();
  46731. };
  46732. /**
  46733. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46734. * @param effect The effect to update
  46735. * @param lightIndex The index of the light in the effect to update
  46736. * @returns The spot light
  46737. */
  46738. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46739. var normalizeDirection;
  46740. if (this.computeTransformedInformation()) {
  46741. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46742. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46743. }
  46744. else {
  46745. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46746. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46747. }
  46748. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46749. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46750. if (this._projectionTextureViewLightDirty) {
  46751. this._computeProjectionTextureViewLightMatrix();
  46752. }
  46753. if (this._projectionTextureProjectionLightDirty) {
  46754. this._computeProjectionTextureProjectionLightMatrix();
  46755. }
  46756. if (this._projectionTextureDirty) {
  46757. this._computeProjectionTextureMatrix();
  46758. }
  46759. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46760. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46761. }
  46762. return this;
  46763. };
  46764. /**
  46765. * Disposes the light and the associated resources.
  46766. */
  46767. SpotLight.prototype.dispose = function () {
  46768. _super.prototype.dispose.call(this);
  46769. if (this._projectionTexture) {
  46770. this._projectionTexture.dispose();
  46771. }
  46772. };
  46773. __decorate([
  46774. BABYLON.serialize()
  46775. ], SpotLight.prototype, "angle", null);
  46776. __decorate([
  46777. BABYLON.serialize()
  46778. ], SpotLight.prototype, "shadowAngleScale", null);
  46779. __decorate([
  46780. BABYLON.serialize()
  46781. ], SpotLight.prototype, "exponent", void 0);
  46782. __decorate([
  46783. BABYLON.serialize()
  46784. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46785. __decorate([
  46786. BABYLON.serialize()
  46787. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46788. __decorate([
  46789. BABYLON.serialize()
  46790. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46791. __decorate([
  46792. BABYLON.serializeAsTexture("projectedLightTexture")
  46793. ], SpotLight.prototype, "_projectionTexture", void 0);
  46794. return SpotLight;
  46795. }(BABYLON.ShadowLight));
  46796. BABYLON.SpotLight = SpotLight;
  46797. })(BABYLON || (BABYLON = {}));
  46798. //# sourceMappingURL=babylon.spotLight.js.map
  46799. "use strict";
  46800. var BABYLON;
  46801. (function (BABYLON) {
  46802. /**
  46803. * Class used to override all child animations of a given target
  46804. */
  46805. var AnimationPropertiesOverride = /** @class */ (function () {
  46806. function AnimationPropertiesOverride() {
  46807. /**
  46808. * Gets or sets a value indicating if animation blending must be used
  46809. */
  46810. this.enableBlending = false;
  46811. /**
  46812. * Gets or sets the blending speed to use when enableBlending is true
  46813. */
  46814. this.blendingSpeed = 0.01;
  46815. /**
  46816. * Gets or sets the default loop mode to use
  46817. */
  46818. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46819. }
  46820. return AnimationPropertiesOverride;
  46821. }());
  46822. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46823. })(BABYLON || (BABYLON = {}));
  46824. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46825. "use strict";
  46826. var BABYLON;
  46827. (function (BABYLON) {
  46828. var AnimationRange = /** @class */ (function () {
  46829. function AnimationRange(name, from, to) {
  46830. this.name = name;
  46831. this.from = from;
  46832. this.to = to;
  46833. }
  46834. AnimationRange.prototype.clone = function () {
  46835. return new AnimationRange(this.name, this.from, this.to);
  46836. };
  46837. return AnimationRange;
  46838. }());
  46839. BABYLON.AnimationRange = AnimationRange;
  46840. /**
  46841. * Composed of a frame, and an action function
  46842. */
  46843. var AnimationEvent = /** @class */ (function () {
  46844. function AnimationEvent(frame, action, onlyOnce) {
  46845. this.frame = frame;
  46846. this.action = action;
  46847. this.onlyOnce = onlyOnce;
  46848. this.isDone = false;
  46849. }
  46850. return AnimationEvent;
  46851. }());
  46852. BABYLON.AnimationEvent = AnimationEvent;
  46853. var PathCursor = /** @class */ (function () {
  46854. function PathCursor(path) {
  46855. this.path = path;
  46856. this._onchange = new Array();
  46857. this.value = 0;
  46858. this.animations = new Array();
  46859. }
  46860. PathCursor.prototype.getPoint = function () {
  46861. var point = this.path.getPointAtLengthPosition(this.value);
  46862. return new BABYLON.Vector3(point.x, 0, point.y);
  46863. };
  46864. PathCursor.prototype.moveAhead = function (step) {
  46865. if (step === void 0) { step = 0.002; }
  46866. this.move(step);
  46867. return this;
  46868. };
  46869. PathCursor.prototype.moveBack = function (step) {
  46870. if (step === void 0) { step = 0.002; }
  46871. this.move(-step);
  46872. return this;
  46873. };
  46874. PathCursor.prototype.move = function (step) {
  46875. if (Math.abs(step) > 1) {
  46876. throw "step size should be less than 1.";
  46877. }
  46878. this.value += step;
  46879. this.ensureLimits();
  46880. this.raiseOnChange();
  46881. return this;
  46882. };
  46883. PathCursor.prototype.ensureLimits = function () {
  46884. while (this.value > 1) {
  46885. this.value -= 1;
  46886. }
  46887. while (this.value < 0) {
  46888. this.value += 1;
  46889. }
  46890. return this;
  46891. };
  46892. // used by animation engine
  46893. PathCursor.prototype.raiseOnChange = function () {
  46894. var _this = this;
  46895. this._onchange.forEach(function (f) { return f(_this); });
  46896. return this;
  46897. };
  46898. PathCursor.prototype.onchange = function (f) {
  46899. this._onchange.push(f);
  46900. return this;
  46901. };
  46902. return PathCursor;
  46903. }());
  46904. BABYLON.PathCursor = PathCursor;
  46905. var AnimationKeyInterpolation;
  46906. (function (AnimationKeyInterpolation) {
  46907. /**
  46908. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46909. */
  46910. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46911. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46912. var Animation = /** @class */ (function () {
  46913. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46914. this.name = name;
  46915. this.targetProperty = targetProperty;
  46916. this.framePerSecond = framePerSecond;
  46917. this.dataType = dataType;
  46918. this.loopMode = loopMode;
  46919. this.enableBlending = enableBlending;
  46920. this._runtimeAnimations = new Array();
  46921. // The set of event that will be linked to this animation
  46922. this._events = new Array();
  46923. this.blendingSpeed = 0.01;
  46924. this._ranges = {};
  46925. this.targetPropertyPath = targetProperty.split(".");
  46926. this.dataType = dataType;
  46927. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46928. }
  46929. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46930. var dataType = undefined;
  46931. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46932. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46933. }
  46934. else if (from instanceof BABYLON.Quaternion) {
  46935. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46936. }
  46937. else if (from instanceof BABYLON.Vector3) {
  46938. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46939. }
  46940. else if (from instanceof BABYLON.Vector2) {
  46941. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46942. }
  46943. else if (from instanceof BABYLON.Color3) {
  46944. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46945. }
  46946. else if (from instanceof BABYLON.Size) {
  46947. dataType = Animation.ANIMATIONTYPE_SIZE;
  46948. }
  46949. if (dataType == undefined) {
  46950. return null;
  46951. }
  46952. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46953. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46954. animation.setKeys(keys);
  46955. if (easingFunction !== undefined) {
  46956. animation.setEasingFunction(easingFunction);
  46957. }
  46958. return animation;
  46959. };
  46960. /**
  46961. * Sets up an animation.
  46962. * @param property the property to animate
  46963. * @param animationType the animation type to apply
  46964. * @param easingFunction the easing function used in the animation
  46965. * @returns The created animation
  46966. */
  46967. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46968. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46969. animation.setEasingFunction(easingFunction);
  46970. return animation;
  46971. };
  46972. /**
  46973. * Create and start an animation on a node
  46974. * @param {string} name defines the name of the global animation that will be run on all nodes
  46975. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46976. * @param {string} targetProperty defines property to animate
  46977. * @param {number} framePerSecond defines the number of frame per second yo use
  46978. * @param {number} totalFrame defines the number of frames in total
  46979. * @param {any} from defines the initial value
  46980. * @param {any} to defines the final value
  46981. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46982. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46983. * @param onAnimationEnd defines the callback to call when animation end
  46984. * @returns the animatable created for this animation
  46985. */
  46986. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46987. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46988. if (!animation) {
  46989. return null;
  46990. }
  46991. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46992. };
  46993. /**
  46994. * Create and start an animation on a node and its descendants
  46995. * @param {string} name defines the name of the global animation that will be run on all nodes
  46996. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46997. * @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.
  46998. * @param {string} targetProperty defines property to animate
  46999. * @param {number} framePerSecond defines the number of frame per second yo use
  47000. * @param {number} totalFrame defines the number of frames in total
  47001. * @param {any} from defines the initial value
  47002. * @param {any} to defines the final value
  47003. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47004. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47005. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  47006. * @returns the list of animatables created for all nodes
  47007. * @example https://www.babylonjs-playground.com/#MH0VLI
  47008. */
  47009. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47010. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47011. if (!animation) {
  47012. return null;
  47013. }
  47014. var scene = node.getScene();
  47015. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47016. };
  47017. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47018. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47019. if (!animation) {
  47020. return null;
  47021. }
  47022. node.animations.push(animation);
  47023. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47024. };
  47025. /**
  47026. * Transition property of the Camera to the target Value.
  47027. * @param property The property to transition
  47028. * @param targetValue The target Value of the property
  47029. * @param host The object where the property to animate belongs
  47030. * @param scene Scene used to run the animation
  47031. * @param frameRate Framerate (in frame/s) to use
  47032. * @param transition The transition type we want to use
  47033. * @param duration The duration of the animation, in milliseconds
  47034. * @param onAnimationEnd Call back trigger at the end of the animation.
  47035. */
  47036. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47037. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47038. if (duration <= 0) {
  47039. host[property] = targetValue;
  47040. if (onAnimationEnd) {
  47041. onAnimationEnd();
  47042. }
  47043. return null;
  47044. }
  47045. var endFrame = frameRate * (duration / 1000);
  47046. transition.setKeys([{
  47047. frame: 0,
  47048. value: host[property].clone ? host[property].clone() : host[property]
  47049. },
  47050. {
  47051. frame: endFrame,
  47052. value: targetValue
  47053. }]);
  47054. if (!host.animations) {
  47055. host.animations = [];
  47056. }
  47057. host.animations.push(transition);
  47058. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47059. animation.onAnimationEnd = onAnimationEnd;
  47060. return animation;
  47061. };
  47062. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47063. /**
  47064. * Return the array of runtime animations currently using this animation
  47065. */
  47066. get: function () {
  47067. return this._runtimeAnimations;
  47068. },
  47069. enumerable: true,
  47070. configurable: true
  47071. });
  47072. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47073. get: function () {
  47074. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47075. var runtimeAnimation = _a[_i];
  47076. if (!runtimeAnimation.isStopped) {
  47077. return true;
  47078. }
  47079. }
  47080. return false;
  47081. },
  47082. enumerable: true,
  47083. configurable: true
  47084. });
  47085. // Methods
  47086. /**
  47087. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47088. */
  47089. Animation.prototype.toString = function (fullDetails) {
  47090. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47091. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47092. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47093. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47094. if (fullDetails) {
  47095. ret += ", Ranges: {";
  47096. var first = true;
  47097. for (var name in this._ranges) {
  47098. if (first) {
  47099. ret += ", ";
  47100. first = false;
  47101. }
  47102. ret += name;
  47103. }
  47104. ret += "}";
  47105. }
  47106. return ret;
  47107. };
  47108. /**
  47109. * Add an event to this animation.
  47110. */
  47111. Animation.prototype.addEvent = function (event) {
  47112. this._events.push(event);
  47113. };
  47114. /**
  47115. * Remove all events found at the given frame
  47116. * @param frame
  47117. */
  47118. Animation.prototype.removeEvents = function (frame) {
  47119. for (var index = 0; index < this._events.length; index++) {
  47120. if (this._events[index].frame === frame) {
  47121. this._events.splice(index, 1);
  47122. index--;
  47123. }
  47124. }
  47125. };
  47126. Animation.prototype.getEvents = function () {
  47127. return this._events;
  47128. };
  47129. Animation.prototype.createRange = function (name, from, to) {
  47130. // check name not already in use; could happen for bones after serialized
  47131. if (!this._ranges[name]) {
  47132. this._ranges[name] = new AnimationRange(name, from, to);
  47133. }
  47134. };
  47135. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47136. if (deleteFrames === void 0) { deleteFrames = true; }
  47137. var range = this._ranges[name];
  47138. if (!range) {
  47139. return;
  47140. }
  47141. if (deleteFrames) {
  47142. var from = range.from;
  47143. var to = range.to;
  47144. // this loop MUST go high to low for multiple splices to work
  47145. for (var key = this._keys.length - 1; key >= 0; key--) {
  47146. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47147. this._keys.splice(key, 1);
  47148. }
  47149. }
  47150. }
  47151. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47152. };
  47153. Animation.prototype.getRange = function (name) {
  47154. return this._ranges[name];
  47155. };
  47156. Animation.prototype.getKeys = function () {
  47157. return this._keys;
  47158. };
  47159. Animation.prototype.getHighestFrame = function () {
  47160. var ret = 0;
  47161. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47162. if (ret < this._keys[key].frame) {
  47163. ret = this._keys[key].frame;
  47164. }
  47165. }
  47166. return ret;
  47167. };
  47168. Animation.prototype.getEasingFunction = function () {
  47169. return this._easingFunction;
  47170. };
  47171. Animation.prototype.setEasingFunction = function (easingFunction) {
  47172. this._easingFunction = easingFunction;
  47173. };
  47174. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47175. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47176. };
  47177. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47178. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47179. };
  47180. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47181. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47182. };
  47183. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47184. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47185. };
  47186. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47187. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47188. };
  47189. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47190. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47191. };
  47192. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47193. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47194. };
  47195. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47196. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47197. };
  47198. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47199. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47200. };
  47201. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47202. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47203. };
  47204. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47205. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47206. };
  47207. Animation.prototype.clone = function () {
  47208. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47209. clone.enableBlending = this.enableBlending;
  47210. clone.blendingSpeed = this.blendingSpeed;
  47211. if (this._keys) {
  47212. clone.setKeys(this._keys);
  47213. }
  47214. if (this._ranges) {
  47215. clone._ranges = {};
  47216. for (var name in this._ranges) {
  47217. var range = this._ranges[name];
  47218. if (!range) {
  47219. continue;
  47220. }
  47221. clone._ranges[name] = range.clone();
  47222. }
  47223. }
  47224. return clone;
  47225. };
  47226. Animation.prototype.setKeys = function (values) {
  47227. this._keys = values.slice(0);
  47228. };
  47229. Animation.prototype.serialize = function () {
  47230. var serializationObject = {};
  47231. serializationObject.name = this.name;
  47232. serializationObject.property = this.targetProperty;
  47233. serializationObject.framePerSecond = this.framePerSecond;
  47234. serializationObject.dataType = this.dataType;
  47235. serializationObject.loopBehavior = this.loopMode;
  47236. serializationObject.enableBlending = this.enableBlending;
  47237. serializationObject.blendingSpeed = this.blendingSpeed;
  47238. var dataType = this.dataType;
  47239. serializationObject.keys = [];
  47240. var keys = this.getKeys();
  47241. for (var index = 0; index < keys.length; index++) {
  47242. var animationKey = keys[index];
  47243. var key = {};
  47244. key.frame = animationKey.frame;
  47245. switch (dataType) {
  47246. case Animation.ANIMATIONTYPE_FLOAT:
  47247. key.values = [animationKey.value];
  47248. break;
  47249. case Animation.ANIMATIONTYPE_QUATERNION:
  47250. case Animation.ANIMATIONTYPE_MATRIX:
  47251. case Animation.ANIMATIONTYPE_VECTOR3:
  47252. case Animation.ANIMATIONTYPE_COLOR3:
  47253. key.values = animationKey.value.asArray();
  47254. break;
  47255. }
  47256. serializationObject.keys.push(key);
  47257. }
  47258. serializationObject.ranges = [];
  47259. for (var name in this._ranges) {
  47260. var source = this._ranges[name];
  47261. if (!source) {
  47262. continue;
  47263. }
  47264. var range = {};
  47265. range.name = name;
  47266. range.from = source.from;
  47267. range.to = source.to;
  47268. serializationObject.ranges.push(range);
  47269. }
  47270. return serializationObject;
  47271. };
  47272. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47273. get: function () {
  47274. return Animation._ANIMATIONTYPE_FLOAT;
  47275. },
  47276. enumerable: true,
  47277. configurable: true
  47278. });
  47279. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47280. get: function () {
  47281. return Animation._ANIMATIONTYPE_VECTOR3;
  47282. },
  47283. enumerable: true,
  47284. configurable: true
  47285. });
  47286. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47287. get: function () {
  47288. return Animation._ANIMATIONTYPE_VECTOR2;
  47289. },
  47290. enumerable: true,
  47291. configurable: true
  47292. });
  47293. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47294. get: function () {
  47295. return Animation._ANIMATIONTYPE_SIZE;
  47296. },
  47297. enumerable: true,
  47298. configurable: true
  47299. });
  47300. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47301. get: function () {
  47302. return Animation._ANIMATIONTYPE_QUATERNION;
  47303. },
  47304. enumerable: true,
  47305. configurable: true
  47306. });
  47307. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47308. get: function () {
  47309. return Animation._ANIMATIONTYPE_MATRIX;
  47310. },
  47311. enumerable: true,
  47312. configurable: true
  47313. });
  47314. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47315. get: function () {
  47316. return Animation._ANIMATIONTYPE_COLOR3;
  47317. },
  47318. enumerable: true,
  47319. configurable: true
  47320. });
  47321. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47322. get: function () {
  47323. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47324. },
  47325. enumerable: true,
  47326. configurable: true
  47327. });
  47328. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47329. get: function () {
  47330. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47331. },
  47332. enumerable: true,
  47333. configurable: true
  47334. });
  47335. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47336. get: function () {
  47337. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47338. },
  47339. enumerable: true,
  47340. configurable: true
  47341. });
  47342. Animation.Parse = function (parsedAnimation) {
  47343. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47344. var dataType = parsedAnimation.dataType;
  47345. var keys = [];
  47346. var data;
  47347. var index;
  47348. if (parsedAnimation.enableBlending) {
  47349. animation.enableBlending = parsedAnimation.enableBlending;
  47350. }
  47351. if (parsedAnimation.blendingSpeed) {
  47352. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47353. }
  47354. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47355. var key = parsedAnimation.keys[index];
  47356. var inTangent;
  47357. var outTangent;
  47358. switch (dataType) {
  47359. case Animation.ANIMATIONTYPE_FLOAT:
  47360. data = key.values[0];
  47361. if (key.values.length >= 1) {
  47362. inTangent = key.values[1];
  47363. }
  47364. if (key.values.length >= 2) {
  47365. outTangent = key.values[2];
  47366. }
  47367. break;
  47368. case Animation.ANIMATIONTYPE_QUATERNION:
  47369. data = BABYLON.Quaternion.FromArray(key.values);
  47370. if (key.values.length >= 8) {
  47371. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47372. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47373. inTangent = _inTangent;
  47374. }
  47375. }
  47376. if (key.values.length >= 12) {
  47377. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47378. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47379. outTangent = _outTangent;
  47380. }
  47381. }
  47382. break;
  47383. case Animation.ANIMATIONTYPE_MATRIX:
  47384. data = BABYLON.Matrix.FromArray(key.values);
  47385. break;
  47386. case Animation.ANIMATIONTYPE_COLOR3:
  47387. data = BABYLON.Color3.FromArray(key.values);
  47388. break;
  47389. case Animation.ANIMATIONTYPE_VECTOR3:
  47390. default:
  47391. data = BABYLON.Vector3.FromArray(key.values);
  47392. break;
  47393. }
  47394. var keyData = {};
  47395. keyData.frame = key.frame;
  47396. keyData.value = data;
  47397. if (inTangent != undefined) {
  47398. keyData.inTangent = inTangent;
  47399. }
  47400. if (outTangent != undefined) {
  47401. keyData.outTangent = outTangent;
  47402. }
  47403. keys.push(keyData);
  47404. }
  47405. animation.setKeys(keys);
  47406. if (parsedAnimation.ranges) {
  47407. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47408. data = parsedAnimation.ranges[index];
  47409. animation.createRange(data.name, data.from, data.to);
  47410. }
  47411. }
  47412. return animation;
  47413. };
  47414. Animation.AppendSerializedAnimations = function (source, destination) {
  47415. if (source.animations) {
  47416. destination.animations = [];
  47417. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47418. var animation = source.animations[animationIndex];
  47419. destination.animations.push(animation.serialize());
  47420. }
  47421. }
  47422. };
  47423. Animation.AllowMatricesInterpolation = false;
  47424. // Statics
  47425. Animation._ANIMATIONTYPE_FLOAT = 0;
  47426. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47427. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47428. Animation._ANIMATIONTYPE_MATRIX = 3;
  47429. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47430. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47431. Animation._ANIMATIONTYPE_SIZE = 6;
  47432. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47433. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47434. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47435. return Animation;
  47436. }());
  47437. BABYLON.Animation = Animation;
  47438. })(BABYLON || (BABYLON = {}));
  47439. //# sourceMappingURL=babylon.animation.js.map
  47440. "use strict";
  47441. var BABYLON;
  47442. (function (BABYLON) {
  47443. /**
  47444. * This class defines the direct association between an animation and a target
  47445. */
  47446. var TargetedAnimation = /** @class */ (function () {
  47447. function TargetedAnimation() {
  47448. }
  47449. return TargetedAnimation;
  47450. }());
  47451. BABYLON.TargetedAnimation = TargetedAnimation;
  47452. /**
  47453. * Use this class to create coordinated animations on multiple targets
  47454. */
  47455. var AnimationGroup = /** @class */ (function () {
  47456. function AnimationGroup(name, scene) {
  47457. if (scene === void 0) { scene = null; }
  47458. this.name = name;
  47459. this._targetedAnimations = new Array();
  47460. this._animatables = new Array();
  47461. this._from = Number.MAX_VALUE;
  47462. this._to = -Number.MAX_VALUE;
  47463. this._speedRatio = 1;
  47464. this.onAnimationEndObservable = new BABYLON.Observable();
  47465. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47466. this._scene.animationGroups.push(this);
  47467. }
  47468. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47469. /**
  47470. * Define if the animations are started
  47471. */
  47472. get: function () {
  47473. return this._isStarted;
  47474. },
  47475. enumerable: true,
  47476. configurable: true
  47477. });
  47478. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47479. /**
  47480. * Gets or sets the speed ratio to use for all animations
  47481. */
  47482. get: function () {
  47483. return this._speedRatio;
  47484. },
  47485. /**
  47486. * Gets or sets the speed ratio to use for all animations
  47487. */
  47488. set: function (value) {
  47489. if (this._speedRatio === value) {
  47490. return;
  47491. }
  47492. this._speedRatio = value;
  47493. for (var index = 0; index < this._animatables.length; index++) {
  47494. var animatable = this._animatables[index];
  47495. animatable.speedRatio = this._speedRatio;
  47496. }
  47497. },
  47498. enumerable: true,
  47499. configurable: true
  47500. });
  47501. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47502. /**
  47503. * Gets the targeted animations for this animation group
  47504. */
  47505. get: function () {
  47506. return this._targetedAnimations;
  47507. },
  47508. enumerable: true,
  47509. configurable: true
  47510. });
  47511. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47512. /**
  47513. * returning the list of animatables controlled by this animation group.
  47514. */
  47515. get: function () {
  47516. return this._animatables;
  47517. },
  47518. enumerable: true,
  47519. configurable: true
  47520. });
  47521. /**
  47522. * Add an animation (with its target) in the group
  47523. * @param animation defines the animation we want to add
  47524. * @param target defines the target of the animation
  47525. * @returns the {BABYLON.TargetedAnimation} object
  47526. */
  47527. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47528. var targetedAnimation = {
  47529. animation: animation,
  47530. target: target
  47531. };
  47532. var keys = animation.getKeys();
  47533. if (this._from > keys[0].frame) {
  47534. this._from = keys[0].frame;
  47535. }
  47536. if (this._to < keys[keys.length - 1].frame) {
  47537. this._to = keys[keys.length - 1].frame;
  47538. }
  47539. this._targetedAnimations.push(targetedAnimation);
  47540. return targetedAnimation;
  47541. };
  47542. /**
  47543. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47544. * It can add constant keys at begin or end
  47545. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47546. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47547. */
  47548. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47549. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47550. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47551. beginFrame = Math.max(beginFrame, this._from);
  47552. endFrame = Math.min(endFrame, this._to);
  47553. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47554. var targetedAnimation = this._targetedAnimations[index];
  47555. var keys = targetedAnimation.animation.getKeys();
  47556. var startKey = keys[0];
  47557. var endKey = keys[keys.length - 1];
  47558. if (startKey.frame > beginFrame) {
  47559. var newKey = {
  47560. frame: beginFrame,
  47561. value: startKey.value,
  47562. inTangent: startKey.inTangent,
  47563. outTangent: startKey.outTangent,
  47564. interpolation: startKey.interpolation
  47565. };
  47566. keys.splice(0, 0, newKey);
  47567. }
  47568. if (endKey.frame < endFrame) {
  47569. var newKey = {
  47570. frame: endFrame,
  47571. value: endKey.value,
  47572. inTangent: endKey.outTangent,
  47573. outTangent: endKey.outTangent,
  47574. interpolation: endKey.interpolation
  47575. };
  47576. keys.push(newKey);
  47577. }
  47578. }
  47579. return this;
  47580. };
  47581. /**
  47582. * Start all animations on given targets
  47583. * @param loop defines if animations must loop
  47584. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47585. * @param from defines the from key (optional)
  47586. * @param to defines the to key (optional)
  47587. * @returns the current animation group
  47588. */
  47589. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  47590. var _this = this;
  47591. if (loop === void 0) { loop = false; }
  47592. if (speedRatio === void 0) { speedRatio = 1; }
  47593. if (this._isStarted || this._targetedAnimations.length === 0) {
  47594. return this;
  47595. }
  47596. var _loop_1 = function () {
  47597. var targetedAnimation = this_1._targetedAnimations[index];
  47598. if (!targetedAnimation.target.animations) {
  47599. targetedAnimation.target.animations = [];
  47600. }
  47601. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  47602. targetedAnimation.target.animations.push(targetedAnimation.animation);
  47603. }
  47604. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  47605. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47606. }));
  47607. };
  47608. var this_1 = this;
  47609. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47610. _loop_1();
  47611. }
  47612. this._speedRatio = speedRatio;
  47613. this._isStarted = true;
  47614. return this;
  47615. };
  47616. /**
  47617. * Pause all animations
  47618. */
  47619. AnimationGroup.prototype.pause = function () {
  47620. if (!this._isStarted) {
  47621. return this;
  47622. }
  47623. for (var index = 0; index < this._animatables.length; index++) {
  47624. var animatable = this._animatables[index];
  47625. animatable.pause();
  47626. }
  47627. return this;
  47628. };
  47629. /**
  47630. * Play all animations to initial state
  47631. * This function will start() the animations if they were not started or will restart() them if they were paused
  47632. * @param loop defines if animations must loop
  47633. */
  47634. AnimationGroup.prototype.play = function (loop) {
  47635. if (this.isStarted) {
  47636. if (loop !== undefined) {
  47637. for (var index = 0; index < this._animatables.length; index++) {
  47638. var animatable = this._animatables[index];
  47639. animatable.loopAnimation = loop;
  47640. }
  47641. }
  47642. this.restart();
  47643. }
  47644. else {
  47645. this.start(loop, this._speedRatio);
  47646. }
  47647. return this;
  47648. };
  47649. /**
  47650. * Reset all animations to initial state
  47651. */
  47652. AnimationGroup.prototype.reset = function () {
  47653. if (!this._isStarted) {
  47654. return this;
  47655. }
  47656. for (var index = 0; index < this._animatables.length; index++) {
  47657. var animatable = this._animatables[index];
  47658. animatable.reset();
  47659. }
  47660. return this;
  47661. };
  47662. /**
  47663. * Restart animations from key 0
  47664. */
  47665. AnimationGroup.prototype.restart = function () {
  47666. if (!this._isStarted) {
  47667. return this;
  47668. }
  47669. for (var index = 0; index < this._animatables.length; index++) {
  47670. var animatable = this._animatables[index];
  47671. animatable.restart();
  47672. }
  47673. return this;
  47674. };
  47675. /**
  47676. * Stop all animations
  47677. */
  47678. AnimationGroup.prototype.stop = function () {
  47679. if (!this._isStarted) {
  47680. return this;
  47681. }
  47682. for (var index = 0; index < this._animatables.length; index++) {
  47683. var animatable = this._animatables[index];
  47684. animatable.stop();
  47685. }
  47686. this._isStarted = false;
  47687. return this;
  47688. };
  47689. /**
  47690. * Goes to a specific frame in this animation group
  47691. *
  47692. * @param frame the frame number to go to
  47693. * @return the animationGroup
  47694. */
  47695. AnimationGroup.prototype.goToFrame = function (frame) {
  47696. if (!this._isStarted) {
  47697. return this;
  47698. }
  47699. for (var index = 0; index < this._animatables.length; index++) {
  47700. var animatable = this._animatables[index];
  47701. animatable.goToFrame(frame);
  47702. }
  47703. return this;
  47704. };
  47705. /**
  47706. * Dispose all associated resources
  47707. */
  47708. AnimationGroup.prototype.dispose = function () {
  47709. this._targetedAnimations = [];
  47710. this._animatables = [];
  47711. var index = this._scene.animationGroups.indexOf(this);
  47712. if (index > -1) {
  47713. this._scene.animationGroups.splice(index, 1);
  47714. }
  47715. };
  47716. return AnimationGroup;
  47717. }());
  47718. BABYLON.AnimationGroup = AnimationGroup;
  47719. })(BABYLON || (BABYLON = {}));
  47720. //# sourceMappingURL=babylon.animationGroup.js.map
  47721. "use strict";
  47722. var BABYLON;
  47723. (function (BABYLON) {
  47724. var RuntimeAnimation = /** @class */ (function () {
  47725. /**
  47726. * Create a new RuntimeAnimation object
  47727. * @param target defines the target of the animation
  47728. * @param animation defines the source {BABYLON.Animation} object
  47729. * @param scene defines the hosting scene
  47730. * @param host defines the initiating Animatable
  47731. */
  47732. function RuntimeAnimation(target, animation, scene, host) {
  47733. this._currentFrame = 0;
  47734. this._offsetsCache = {};
  47735. this._highLimitsCache = {};
  47736. this._stopped = false;
  47737. this._blendingFactor = 0;
  47738. this._targetPath = "";
  47739. this._weight = 1.0;
  47740. this._ratioOffset = 0;
  47741. this._previousDelay = 0;
  47742. this._previousRatio = 0;
  47743. this._animation = animation;
  47744. this._target = target;
  47745. this._scene = scene;
  47746. this._host = host;
  47747. animation._runtimeAnimations.push(this);
  47748. }
  47749. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  47750. /**
  47751. * Gets the current frame
  47752. */
  47753. get: function () {
  47754. return this._currentFrame;
  47755. },
  47756. enumerable: true,
  47757. configurable: true
  47758. });
  47759. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47760. /**
  47761. * Gets the weight of the runtime animation
  47762. */
  47763. get: function () {
  47764. return this._weight;
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47770. /**
  47771. * Gets the original value of the runtime animation
  47772. */
  47773. get: function () {
  47774. return this._originalValue;
  47775. },
  47776. enumerable: true,
  47777. configurable: true
  47778. });
  47779. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47780. /**
  47781. * Gets the current value of the runtime animation
  47782. */
  47783. get: function () {
  47784. return this._currentValue;
  47785. },
  47786. enumerable: true,
  47787. configurable: true
  47788. });
  47789. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47790. /**
  47791. * Gets the path where to store the animated value in the target
  47792. */
  47793. get: function () {
  47794. return this._targetPath;
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47800. /**
  47801. * Gets the actual target of the runtime animation
  47802. */
  47803. get: function () {
  47804. return this._activeTarget;
  47805. },
  47806. enumerable: true,
  47807. configurable: true
  47808. });
  47809. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47810. get: function () {
  47811. return this._animation;
  47812. },
  47813. enumerable: true,
  47814. configurable: true
  47815. });
  47816. RuntimeAnimation.prototype.reset = function () {
  47817. this._offsetsCache = {};
  47818. this._highLimitsCache = {};
  47819. this._currentFrame = 0;
  47820. this._blendingFactor = 0;
  47821. this._originalValue = null;
  47822. };
  47823. RuntimeAnimation.prototype.isStopped = function () {
  47824. return this._stopped;
  47825. };
  47826. RuntimeAnimation.prototype.dispose = function () {
  47827. var index = this._animation.runtimeAnimations.indexOf(this);
  47828. if (index > -1) {
  47829. this._animation.runtimeAnimations.splice(index, 1);
  47830. }
  47831. };
  47832. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47833. if (typeof value === "function") {
  47834. return value();
  47835. }
  47836. return value;
  47837. };
  47838. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47839. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47840. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47841. }
  47842. this._currentFrame = currentFrame;
  47843. var keys = this._animation.getKeys();
  47844. // Try to get a hash to find the right key
  47845. 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));
  47846. if (keys[startKeyIndex].frame >= currentFrame) {
  47847. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47848. startKeyIndex--;
  47849. }
  47850. }
  47851. for (var key = startKeyIndex; key < keys.length; key++) {
  47852. var endKey = keys[key + 1];
  47853. if (endKey.frame >= currentFrame) {
  47854. var startKey = keys[key];
  47855. var startValue = this._getKeyValue(startKey.value);
  47856. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47857. return startValue;
  47858. }
  47859. var endValue = this._getKeyValue(endKey.value);
  47860. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47861. var frameDelta = endKey.frame - startKey.frame;
  47862. // gradient : percent of currentFrame between the frame inf and the frame sup
  47863. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47864. // check for easingFunction and correction of gradient
  47865. var easingFunction = this._animation.getEasingFunction();
  47866. if (easingFunction != null) {
  47867. gradient = easingFunction.ease(gradient);
  47868. }
  47869. switch (this._animation.dataType) {
  47870. // Float
  47871. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47872. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47873. switch (loopMode) {
  47874. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47875. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47876. return floatValue;
  47877. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47878. return offsetValue * repeatCount + floatValue;
  47879. }
  47880. break;
  47881. // Quaternion
  47882. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47883. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47884. switch (loopMode) {
  47885. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47886. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47887. return quatValue;
  47888. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47889. return quatValue.add(offsetValue.scale(repeatCount));
  47890. }
  47891. return quatValue;
  47892. // Vector3
  47893. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47894. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47895. switch (loopMode) {
  47896. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47897. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47898. return vec3Value;
  47899. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47900. return vec3Value.add(offsetValue.scale(repeatCount));
  47901. }
  47902. // Vector2
  47903. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47904. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47905. switch (loopMode) {
  47906. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47907. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47908. return vec2Value;
  47909. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47910. return vec2Value.add(offsetValue.scale(repeatCount));
  47911. }
  47912. // Size
  47913. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47914. switch (loopMode) {
  47915. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47916. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47917. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47918. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47919. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47920. }
  47921. // Color3
  47922. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47923. switch (loopMode) {
  47924. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47925. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47926. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47927. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47928. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47929. }
  47930. // Matrix
  47931. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47932. switch (loopMode) {
  47933. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47934. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47935. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47936. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47937. }
  47938. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47939. return startValue;
  47940. }
  47941. default:
  47942. break;
  47943. }
  47944. break;
  47945. }
  47946. }
  47947. return this._getKeyValue(keys[keys.length - 1].value);
  47948. };
  47949. /**
  47950. * Affect the interpolated value to the target
  47951. * @param currentValue defines the value computed by the animation
  47952. * @param weight defines the weight to apply to this value
  47953. */
  47954. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47955. if (weight === void 0) { weight = 1.0; }
  47956. // Set value
  47957. var path;
  47958. var destination;
  47959. var targetPropertyPath = this._animation.targetPropertyPath;
  47960. if (targetPropertyPath.length > 1) {
  47961. var property = this._target[targetPropertyPath[0]];
  47962. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47963. property = property[targetPropertyPath[index]];
  47964. }
  47965. path = targetPropertyPath[targetPropertyPath.length - 1];
  47966. destination = property;
  47967. }
  47968. else {
  47969. path = targetPropertyPath[0];
  47970. destination = this._target;
  47971. }
  47972. this._targetPath = path;
  47973. this._activeTarget = destination;
  47974. this._weight = weight;
  47975. // Blending
  47976. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47977. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47978. if (enableBlending && this._blendingFactor <= 1.0) {
  47979. if (!this._originalBlendValue) {
  47980. var originalValue = destination[path];
  47981. if (originalValue.clone) {
  47982. this._originalBlendValue = originalValue.clone();
  47983. }
  47984. else {
  47985. this._originalBlendValue = originalValue;
  47986. }
  47987. }
  47988. }
  47989. if (weight !== -1.0) {
  47990. if (!this._originalValue) {
  47991. var originalValue = void 0;
  47992. if (destination.getRestPose) {
  47993. originalValue = destination.getRestPose();
  47994. }
  47995. else {
  47996. originalValue = destination[path];
  47997. }
  47998. if (originalValue.clone) {
  47999. this._originalValue = originalValue.clone();
  48000. }
  48001. else {
  48002. this._originalValue = originalValue;
  48003. }
  48004. }
  48005. }
  48006. if (enableBlending && this._blendingFactor <= 1.0) {
  48007. if (this._originalBlendValue.prototype) {
  48008. if (this._originalBlendValue.prototype.Lerp) {
  48009. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  48010. }
  48011. else {
  48012. this._currentValue = currentValue;
  48013. }
  48014. }
  48015. else if (this._originalBlendValue.m) {
  48016. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  48017. }
  48018. else {
  48019. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  48020. }
  48021. this._blendingFactor += blendingSpeed;
  48022. }
  48023. else {
  48024. this._currentValue = currentValue;
  48025. }
  48026. if (weight !== -1.0) {
  48027. this._scene._registerTargetForLateAnimationBinding(this);
  48028. }
  48029. else {
  48030. destination[path] = this._currentValue;
  48031. }
  48032. if (this._target.markAsDirty) {
  48033. this._target.markAsDirty(this._animation.targetProperty);
  48034. }
  48035. };
  48036. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48037. if (this._target && this._target.animationPropertiesOverride) {
  48038. return this._target.animationPropertiesOverride.loopMode;
  48039. }
  48040. return this._animation.loopMode;
  48041. };
  48042. /**
  48043. * Move the current animation to a given frame
  48044. * @param frame defines the frame to move to
  48045. */
  48046. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48047. var keys = this._animation.getKeys();
  48048. if (frame < keys[0].frame) {
  48049. frame = keys[0].frame;
  48050. }
  48051. else if (frame > keys[keys.length - 1].frame) {
  48052. frame = keys[keys.length - 1].frame;
  48053. }
  48054. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48055. this.setValue(currentValue, -1);
  48056. };
  48057. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48058. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48059. this._ratioOffset = this._previousRatio - newRatio;
  48060. };
  48061. /**
  48062. * Execute the current animation
  48063. * @param delay defines the delay to add to the current frame
  48064. * @param from defines the lower bound of the animation range
  48065. * @param to defines the upper bound of the animation range
  48066. * @param loop defines if the current animation must loop
  48067. * @param speedRatio defines the current speed ratio
  48068. * @param weight defines the weight of the animation (default is -1 so no weight)
  48069. * @returns a boolean indicating if the animation has ended
  48070. */
  48071. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48072. if (weight === void 0) { weight = -1.0; }
  48073. var targetPropertyPath = this._animation.targetPropertyPath;
  48074. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48075. this._stopped = true;
  48076. return false;
  48077. }
  48078. var returnValue = true;
  48079. var keys = this._animation.getKeys();
  48080. // Adding a start key at frame 0 if missing
  48081. if (keys[0].frame !== 0) {
  48082. var newKey = { frame: 0, value: keys[0].value };
  48083. keys.splice(0, 0, newKey);
  48084. }
  48085. // Check limits
  48086. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48087. from = keys[0].frame;
  48088. }
  48089. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48090. to = keys[keys.length - 1].frame;
  48091. }
  48092. //to and from cannot be the same key
  48093. if (from === to) {
  48094. if (from > keys[0].frame) {
  48095. from--;
  48096. }
  48097. else if (to < keys[keys.length - 1].frame) {
  48098. to++;
  48099. }
  48100. }
  48101. // Compute ratio
  48102. var range = to - from;
  48103. var offsetValue;
  48104. // ratio represents the frame delta between from and to
  48105. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48106. var highLimitValue = 0;
  48107. this._previousDelay = delay;
  48108. this._previousRatio = ratio;
  48109. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48110. returnValue = false;
  48111. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48112. }
  48113. else {
  48114. // Get max value if required
  48115. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48116. var keyOffset = to.toString() + from.toString();
  48117. if (!this._offsetsCache[keyOffset]) {
  48118. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48119. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48120. switch (this._animation.dataType) {
  48121. // Float
  48122. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48123. this._offsetsCache[keyOffset] = toValue - fromValue;
  48124. break;
  48125. // Quaternion
  48126. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48127. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48128. break;
  48129. // Vector3
  48130. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48131. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48132. // Vector2
  48133. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48134. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48135. // Size
  48136. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48137. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48138. // Color3
  48139. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48140. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48141. default:
  48142. break;
  48143. }
  48144. this._highLimitsCache[keyOffset] = toValue;
  48145. }
  48146. highLimitValue = this._highLimitsCache[keyOffset];
  48147. offsetValue = this._offsetsCache[keyOffset];
  48148. }
  48149. }
  48150. if (offsetValue === undefined) {
  48151. switch (this._animation.dataType) {
  48152. // Float
  48153. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48154. offsetValue = 0;
  48155. break;
  48156. // Quaternion
  48157. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48158. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48159. break;
  48160. // Vector3
  48161. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48162. offsetValue = BABYLON.Vector3.Zero();
  48163. break;
  48164. // Vector2
  48165. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48166. offsetValue = BABYLON.Vector2.Zero();
  48167. break;
  48168. // Size
  48169. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48170. offsetValue = BABYLON.Size.Zero();
  48171. break;
  48172. // Color3
  48173. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48174. offsetValue = BABYLON.Color3.Black();
  48175. }
  48176. }
  48177. // Compute value
  48178. var repeatCount = (ratio / range) >> 0;
  48179. var currentFrame = returnValue ? from + ratio % range : to;
  48180. // Need to normalize?
  48181. if (this._host && this._host.syncRoot) {
  48182. var syncRoot = this._host.syncRoot;
  48183. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48184. currentFrame = from + (to - from) * hostNormalizedFrame;
  48185. }
  48186. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48187. // Set value
  48188. this.setValue(currentValue, weight);
  48189. // Check events
  48190. var events = this._animation.getEvents();
  48191. for (var index = 0; index < events.length; index++) {
  48192. // Make sure current frame has passed event frame and that event frame is within the current range
  48193. // Also, handle both forward and reverse animations
  48194. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48195. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48196. var event = events[index];
  48197. if (!event.isDone) {
  48198. // If event should be done only once, remove it.
  48199. if (event.onlyOnce) {
  48200. events.splice(index, 1);
  48201. index--;
  48202. }
  48203. event.isDone = true;
  48204. event.action();
  48205. } // Don't do anything if the event has already be done.
  48206. }
  48207. else if (events[index].isDone && !events[index].onlyOnce) {
  48208. // reset event, the animation is looping
  48209. events[index].isDone = false;
  48210. }
  48211. }
  48212. if (!returnValue) {
  48213. this._stopped = true;
  48214. }
  48215. return returnValue;
  48216. };
  48217. return RuntimeAnimation;
  48218. }());
  48219. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48220. })(BABYLON || (BABYLON = {}));
  48221. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48222. "use strict";
  48223. var BABYLON;
  48224. (function (BABYLON) {
  48225. var Animatable = /** @class */ (function () {
  48226. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48227. if (fromFrame === void 0) { fromFrame = 0; }
  48228. if (toFrame === void 0) { toFrame = 100; }
  48229. if (loopAnimation === void 0) { loopAnimation = false; }
  48230. if (speedRatio === void 0) { speedRatio = 1.0; }
  48231. this.target = target;
  48232. this.fromFrame = fromFrame;
  48233. this.toFrame = toFrame;
  48234. this.loopAnimation = loopAnimation;
  48235. this.onAnimationEnd = onAnimationEnd;
  48236. this._localDelayOffset = null;
  48237. this._pausedDelay = null;
  48238. this._runtimeAnimations = new Array();
  48239. this._paused = false;
  48240. this._speedRatio = 1;
  48241. this._weight = -1.0;
  48242. this.animationStarted = false;
  48243. if (animations) {
  48244. this.appendAnimations(target, animations);
  48245. }
  48246. this._speedRatio = speedRatio;
  48247. this._scene = scene;
  48248. scene._activeAnimatables.push(this);
  48249. }
  48250. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48251. /**
  48252. * Gets the root Animatable used to synchronize and normalize animations
  48253. */
  48254. get: function () {
  48255. return this._syncRoot;
  48256. },
  48257. enumerable: true,
  48258. configurable: true
  48259. });
  48260. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48261. /**
  48262. * Gets the current frame of the first RuntimeAnimation
  48263. * Used to synchronize Animatables
  48264. */
  48265. get: function () {
  48266. if (this._runtimeAnimations.length === 0) {
  48267. return 0;
  48268. }
  48269. return this._runtimeAnimations[0].currentFrame;
  48270. },
  48271. enumerable: true,
  48272. configurable: true
  48273. });
  48274. Object.defineProperty(Animatable.prototype, "weight", {
  48275. /**
  48276. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48277. */
  48278. get: function () {
  48279. return this._weight;
  48280. },
  48281. set: function (value) {
  48282. if (value === -1) {
  48283. this._weight = -1;
  48284. return;
  48285. }
  48286. // Else weight must be in [0, 1] range
  48287. this._weight = Math.min(Math.max(value, 0), 1.0);
  48288. },
  48289. enumerable: true,
  48290. configurable: true
  48291. });
  48292. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48293. /**
  48294. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48295. */
  48296. get: function () {
  48297. return this._speedRatio;
  48298. },
  48299. set: function (value) {
  48300. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48301. var animation = this._runtimeAnimations[index];
  48302. animation._prepareForSpeedRatioChange(value);
  48303. }
  48304. this._speedRatio = value;
  48305. },
  48306. enumerable: true,
  48307. configurable: true
  48308. });
  48309. // Methods
  48310. /**
  48311. * Synchronize and normalize current Animatable with a source Animatable.
  48312. * This is useful when using animation weights and when animations are not of the same length
  48313. * @param root defines the root Animatable to synchronize with
  48314. * @returns the current Animatable
  48315. */
  48316. Animatable.prototype.syncWith = function (root) {
  48317. this._syncRoot = root;
  48318. if (root) {
  48319. // Make sure this animatable will animate after the root
  48320. var index = this._scene._activeAnimatables.indexOf(this);
  48321. if (index > -1) {
  48322. this._scene._activeAnimatables.splice(index, 1);
  48323. this._scene._activeAnimatables.push(this);
  48324. }
  48325. }
  48326. return this;
  48327. };
  48328. Animatable.prototype.getAnimations = function () {
  48329. return this._runtimeAnimations;
  48330. };
  48331. Animatable.prototype.appendAnimations = function (target, animations) {
  48332. for (var index = 0; index < animations.length; index++) {
  48333. var animation = animations[index];
  48334. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  48335. }
  48336. };
  48337. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48338. var runtimeAnimations = this._runtimeAnimations;
  48339. for (var index = 0; index < runtimeAnimations.length; index++) {
  48340. if (runtimeAnimations[index].animation.targetProperty === property) {
  48341. return runtimeAnimations[index].animation;
  48342. }
  48343. }
  48344. return null;
  48345. };
  48346. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48347. var runtimeAnimations = this._runtimeAnimations;
  48348. for (var index = 0; index < runtimeAnimations.length; index++) {
  48349. if (runtimeAnimations[index].animation.targetProperty === property) {
  48350. return runtimeAnimations[index];
  48351. }
  48352. }
  48353. return null;
  48354. };
  48355. Animatable.prototype.reset = function () {
  48356. var runtimeAnimations = this._runtimeAnimations;
  48357. for (var index = 0; index < runtimeAnimations.length; index++) {
  48358. runtimeAnimations[index].reset();
  48359. }
  48360. // Reset to original value
  48361. for (index = 0; index < runtimeAnimations.length; index++) {
  48362. var animation = runtimeAnimations[index];
  48363. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48364. }
  48365. this._localDelayOffset = null;
  48366. this._pausedDelay = null;
  48367. };
  48368. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48369. var runtimeAnimations = this._runtimeAnimations;
  48370. for (var index = 0; index < runtimeAnimations.length; index++) {
  48371. runtimeAnimations[index].animation.enableBlending = true;
  48372. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48373. }
  48374. };
  48375. Animatable.prototype.disableBlending = function () {
  48376. var runtimeAnimations = this._runtimeAnimations;
  48377. for (var index = 0; index < runtimeAnimations.length; index++) {
  48378. runtimeAnimations[index].animation.enableBlending = false;
  48379. }
  48380. };
  48381. Animatable.prototype.goToFrame = function (frame) {
  48382. var runtimeAnimations = this._runtimeAnimations;
  48383. if (runtimeAnimations[0]) {
  48384. var fps = runtimeAnimations[0].animation.framePerSecond;
  48385. var currentFrame = runtimeAnimations[0].currentFrame;
  48386. var adjustTime = frame - currentFrame;
  48387. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48388. if (this._localDelayOffset === null) {
  48389. this._localDelayOffset = 0;
  48390. }
  48391. this._localDelayOffset -= delay;
  48392. }
  48393. for (var index = 0; index < runtimeAnimations.length; index++) {
  48394. runtimeAnimations[index].goToFrame(frame);
  48395. }
  48396. };
  48397. Animatable.prototype.pause = function () {
  48398. if (this._paused) {
  48399. return;
  48400. }
  48401. this._paused = true;
  48402. };
  48403. Animatable.prototype.restart = function () {
  48404. this._paused = false;
  48405. };
  48406. Animatable.prototype.stop = function (animationName) {
  48407. if (animationName) {
  48408. var idx = this._scene._activeAnimatables.indexOf(this);
  48409. if (idx > -1) {
  48410. var runtimeAnimations = this._runtimeAnimations;
  48411. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48412. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48413. continue;
  48414. }
  48415. runtimeAnimations[index].dispose();
  48416. runtimeAnimations.splice(index, 1);
  48417. }
  48418. if (runtimeAnimations.length == 0) {
  48419. this._scene._activeAnimatables.splice(idx, 1);
  48420. if (this.onAnimationEnd) {
  48421. this.onAnimationEnd();
  48422. }
  48423. }
  48424. }
  48425. }
  48426. else {
  48427. var index = this._scene._activeAnimatables.indexOf(this);
  48428. if (index > -1) {
  48429. this._scene._activeAnimatables.splice(index, 1);
  48430. var runtimeAnimations = this._runtimeAnimations;
  48431. for (var index = 0; index < runtimeAnimations.length; index++) {
  48432. runtimeAnimations[index].dispose();
  48433. }
  48434. if (this.onAnimationEnd) {
  48435. this.onAnimationEnd();
  48436. }
  48437. }
  48438. }
  48439. };
  48440. Animatable.prototype._animate = function (delay) {
  48441. if (this._paused) {
  48442. this.animationStarted = false;
  48443. if (this._pausedDelay === null) {
  48444. this._pausedDelay = delay;
  48445. }
  48446. return true;
  48447. }
  48448. if (this._localDelayOffset === null) {
  48449. this._localDelayOffset = delay;
  48450. this._pausedDelay = null;
  48451. }
  48452. else if (this._pausedDelay !== null) {
  48453. this._localDelayOffset += delay - this._pausedDelay;
  48454. this._pausedDelay = null;
  48455. }
  48456. if (this._weight === 0) {
  48457. return true;
  48458. }
  48459. // Animating
  48460. var running = false;
  48461. var runtimeAnimations = this._runtimeAnimations;
  48462. var index;
  48463. for (index = 0; index < runtimeAnimations.length; index++) {
  48464. var animation = runtimeAnimations[index];
  48465. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48466. running = running || isRunning;
  48467. }
  48468. this.animationStarted = running;
  48469. if (!running) {
  48470. // Remove from active animatables
  48471. index = this._scene._activeAnimatables.indexOf(this);
  48472. this._scene._activeAnimatables.splice(index, 1);
  48473. // Dispose all runtime animations
  48474. for (index = 0; index < runtimeAnimations.length; index++) {
  48475. runtimeAnimations[index].dispose();
  48476. }
  48477. }
  48478. if (!running && this.onAnimationEnd) {
  48479. this.onAnimationEnd();
  48480. this.onAnimationEnd = null;
  48481. }
  48482. return running;
  48483. };
  48484. return Animatable;
  48485. }());
  48486. BABYLON.Animatable = Animatable;
  48487. })(BABYLON || (BABYLON = {}));
  48488. //# sourceMappingURL=babylon.animatable.js.map
  48489. "use strict";
  48490. var BABYLON;
  48491. (function (BABYLON) {
  48492. var EasingFunction = /** @class */ (function () {
  48493. function EasingFunction() {
  48494. // Properties
  48495. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48496. }
  48497. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48498. get: function () {
  48499. return EasingFunction._EASINGMODE_EASEIN;
  48500. },
  48501. enumerable: true,
  48502. configurable: true
  48503. });
  48504. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48505. get: function () {
  48506. return EasingFunction._EASINGMODE_EASEOUT;
  48507. },
  48508. enumerable: true,
  48509. configurable: true
  48510. });
  48511. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48512. get: function () {
  48513. return EasingFunction._EASINGMODE_EASEINOUT;
  48514. },
  48515. enumerable: true,
  48516. configurable: true
  48517. });
  48518. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48519. var n = Math.min(Math.max(easingMode, 0), 2);
  48520. this._easingMode = n;
  48521. };
  48522. EasingFunction.prototype.getEasingMode = function () {
  48523. return this._easingMode;
  48524. };
  48525. EasingFunction.prototype.easeInCore = function (gradient) {
  48526. throw new Error('You must implement this method');
  48527. };
  48528. EasingFunction.prototype.ease = function (gradient) {
  48529. switch (this._easingMode) {
  48530. case EasingFunction.EASINGMODE_EASEIN:
  48531. return this.easeInCore(gradient);
  48532. case EasingFunction.EASINGMODE_EASEOUT:
  48533. return (1 - this.easeInCore(1 - gradient));
  48534. }
  48535. if (gradient >= 0.5) {
  48536. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48537. }
  48538. return (this.easeInCore(gradient * 2) * 0.5);
  48539. };
  48540. //Statics
  48541. EasingFunction._EASINGMODE_EASEIN = 0;
  48542. EasingFunction._EASINGMODE_EASEOUT = 1;
  48543. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48544. return EasingFunction;
  48545. }());
  48546. BABYLON.EasingFunction = EasingFunction;
  48547. var CircleEase = /** @class */ (function (_super) {
  48548. __extends(CircleEase, _super);
  48549. function CircleEase() {
  48550. return _super !== null && _super.apply(this, arguments) || this;
  48551. }
  48552. CircleEase.prototype.easeInCore = function (gradient) {
  48553. gradient = Math.max(0, Math.min(1, gradient));
  48554. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48555. };
  48556. return CircleEase;
  48557. }(EasingFunction));
  48558. BABYLON.CircleEase = CircleEase;
  48559. var BackEase = /** @class */ (function (_super) {
  48560. __extends(BackEase, _super);
  48561. function BackEase(amplitude) {
  48562. if (amplitude === void 0) { amplitude = 1; }
  48563. var _this = _super.call(this) || this;
  48564. _this.amplitude = amplitude;
  48565. return _this;
  48566. }
  48567. BackEase.prototype.easeInCore = function (gradient) {
  48568. var num = Math.max(0, this.amplitude);
  48569. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48570. };
  48571. return BackEase;
  48572. }(EasingFunction));
  48573. BABYLON.BackEase = BackEase;
  48574. var BounceEase = /** @class */ (function (_super) {
  48575. __extends(BounceEase, _super);
  48576. function BounceEase(bounces, bounciness) {
  48577. if (bounces === void 0) { bounces = 3; }
  48578. if (bounciness === void 0) { bounciness = 2; }
  48579. var _this = _super.call(this) || this;
  48580. _this.bounces = bounces;
  48581. _this.bounciness = bounciness;
  48582. return _this;
  48583. }
  48584. BounceEase.prototype.easeInCore = function (gradient) {
  48585. var y = Math.max(0.0, this.bounces);
  48586. var bounciness = this.bounciness;
  48587. if (bounciness <= 1.0) {
  48588. bounciness = 1.001;
  48589. }
  48590. var num9 = Math.pow(bounciness, y);
  48591. var num5 = 1.0 - bounciness;
  48592. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48593. var num15 = gradient * num4;
  48594. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48595. var num3 = Math.floor(num65);
  48596. var num13 = num3 + 1.0;
  48597. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48598. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48599. var num7 = (num8 + num12) * 0.5;
  48600. var num6 = gradient - num7;
  48601. var num2 = num7 - num8;
  48602. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48603. };
  48604. return BounceEase;
  48605. }(EasingFunction));
  48606. BABYLON.BounceEase = BounceEase;
  48607. var CubicEase = /** @class */ (function (_super) {
  48608. __extends(CubicEase, _super);
  48609. function CubicEase() {
  48610. return _super !== null && _super.apply(this, arguments) || this;
  48611. }
  48612. CubicEase.prototype.easeInCore = function (gradient) {
  48613. return (gradient * gradient * gradient);
  48614. };
  48615. return CubicEase;
  48616. }(EasingFunction));
  48617. BABYLON.CubicEase = CubicEase;
  48618. var ElasticEase = /** @class */ (function (_super) {
  48619. __extends(ElasticEase, _super);
  48620. function ElasticEase(oscillations, springiness) {
  48621. if (oscillations === void 0) { oscillations = 3; }
  48622. if (springiness === void 0) { springiness = 3; }
  48623. var _this = _super.call(this) || this;
  48624. _this.oscillations = oscillations;
  48625. _this.springiness = springiness;
  48626. return _this;
  48627. }
  48628. ElasticEase.prototype.easeInCore = function (gradient) {
  48629. var num2;
  48630. var num3 = Math.max(0.0, this.oscillations);
  48631. var num = Math.max(0.0, this.springiness);
  48632. if (num == 0) {
  48633. num2 = gradient;
  48634. }
  48635. else {
  48636. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48637. }
  48638. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48639. };
  48640. return ElasticEase;
  48641. }(EasingFunction));
  48642. BABYLON.ElasticEase = ElasticEase;
  48643. var ExponentialEase = /** @class */ (function (_super) {
  48644. __extends(ExponentialEase, _super);
  48645. function ExponentialEase(exponent) {
  48646. if (exponent === void 0) { exponent = 2; }
  48647. var _this = _super.call(this) || this;
  48648. _this.exponent = exponent;
  48649. return _this;
  48650. }
  48651. ExponentialEase.prototype.easeInCore = function (gradient) {
  48652. if (this.exponent <= 0) {
  48653. return gradient;
  48654. }
  48655. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48656. };
  48657. return ExponentialEase;
  48658. }(EasingFunction));
  48659. BABYLON.ExponentialEase = ExponentialEase;
  48660. var PowerEase = /** @class */ (function (_super) {
  48661. __extends(PowerEase, _super);
  48662. function PowerEase(power) {
  48663. if (power === void 0) { power = 2; }
  48664. var _this = _super.call(this) || this;
  48665. _this.power = power;
  48666. return _this;
  48667. }
  48668. PowerEase.prototype.easeInCore = function (gradient) {
  48669. var y = Math.max(0.0, this.power);
  48670. return Math.pow(gradient, y);
  48671. };
  48672. return PowerEase;
  48673. }(EasingFunction));
  48674. BABYLON.PowerEase = PowerEase;
  48675. var QuadraticEase = /** @class */ (function (_super) {
  48676. __extends(QuadraticEase, _super);
  48677. function QuadraticEase() {
  48678. return _super !== null && _super.apply(this, arguments) || this;
  48679. }
  48680. QuadraticEase.prototype.easeInCore = function (gradient) {
  48681. return (gradient * gradient);
  48682. };
  48683. return QuadraticEase;
  48684. }(EasingFunction));
  48685. BABYLON.QuadraticEase = QuadraticEase;
  48686. var QuarticEase = /** @class */ (function (_super) {
  48687. __extends(QuarticEase, _super);
  48688. function QuarticEase() {
  48689. return _super !== null && _super.apply(this, arguments) || this;
  48690. }
  48691. QuarticEase.prototype.easeInCore = function (gradient) {
  48692. return (gradient * gradient * gradient * gradient);
  48693. };
  48694. return QuarticEase;
  48695. }(EasingFunction));
  48696. BABYLON.QuarticEase = QuarticEase;
  48697. var QuinticEase = /** @class */ (function (_super) {
  48698. __extends(QuinticEase, _super);
  48699. function QuinticEase() {
  48700. return _super !== null && _super.apply(this, arguments) || this;
  48701. }
  48702. QuinticEase.prototype.easeInCore = function (gradient) {
  48703. return (gradient * gradient * gradient * gradient * gradient);
  48704. };
  48705. return QuinticEase;
  48706. }(EasingFunction));
  48707. BABYLON.QuinticEase = QuinticEase;
  48708. var SineEase = /** @class */ (function (_super) {
  48709. __extends(SineEase, _super);
  48710. function SineEase() {
  48711. return _super !== null && _super.apply(this, arguments) || this;
  48712. }
  48713. SineEase.prototype.easeInCore = function (gradient) {
  48714. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48715. };
  48716. return SineEase;
  48717. }(EasingFunction));
  48718. BABYLON.SineEase = SineEase;
  48719. var BezierCurveEase = /** @class */ (function (_super) {
  48720. __extends(BezierCurveEase, _super);
  48721. function BezierCurveEase(x1, y1, x2, y2) {
  48722. if (x1 === void 0) { x1 = 0; }
  48723. if (y1 === void 0) { y1 = 0; }
  48724. if (x2 === void 0) { x2 = 1; }
  48725. if (y2 === void 0) { y2 = 1; }
  48726. var _this = _super.call(this) || this;
  48727. _this.x1 = x1;
  48728. _this.y1 = y1;
  48729. _this.x2 = x2;
  48730. _this.y2 = y2;
  48731. return _this;
  48732. }
  48733. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48734. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48735. };
  48736. return BezierCurveEase;
  48737. }(EasingFunction));
  48738. BABYLON.BezierCurveEase = BezierCurveEase;
  48739. })(BABYLON || (BABYLON = {}));
  48740. //# sourceMappingURL=babylon.easing.js.map
  48741. "use strict";
  48742. var BABYLON;
  48743. (function (BABYLON) {
  48744. /**
  48745. * A Condition applied to an Action
  48746. */
  48747. var Condition = /** @class */ (function () {
  48748. /**
  48749. * Creates a new Condition
  48750. * @param actionManager the manager of the action the condition is applied to
  48751. */
  48752. function Condition(actionManager) {
  48753. this._actionManager = actionManager;
  48754. }
  48755. /**
  48756. * Check if the current condition is valid
  48757. * @returns a boolean
  48758. */
  48759. Condition.prototype.isValid = function () {
  48760. return true;
  48761. };
  48762. /**
  48763. * Internal only
  48764. * @ignore
  48765. */
  48766. Condition.prototype._getProperty = function (propertyPath) {
  48767. return this._actionManager._getProperty(propertyPath);
  48768. };
  48769. /**
  48770. * Internal only
  48771. * @ignore
  48772. */
  48773. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48774. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48775. };
  48776. /**
  48777. * Serialize placeholder for child classes
  48778. * @returns the serialized object
  48779. */
  48780. Condition.prototype.serialize = function () {
  48781. };
  48782. /**
  48783. * Internal only
  48784. * @ignore
  48785. */
  48786. Condition.prototype._serialize = function (serializedCondition) {
  48787. return {
  48788. type: 2,
  48789. children: [],
  48790. name: serializedCondition.name,
  48791. properties: serializedCondition.properties
  48792. };
  48793. };
  48794. return Condition;
  48795. }());
  48796. BABYLON.Condition = Condition;
  48797. /**
  48798. * Defines specific conditional operators as extensions of Condition
  48799. */
  48800. var ValueCondition = /** @class */ (function (_super) {
  48801. __extends(ValueCondition, _super);
  48802. /**
  48803. * Creates a new ValueCondition
  48804. * @param actionManager manager for the action the condition applies to
  48805. * @param target for the action
  48806. * @param propertyPath path to specify the property of the target the conditional operator uses
  48807. * @param value the vale compared by the conditional operator against the current value of the property
  48808. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  48809. */
  48810. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48811. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48812. var _this = _super.call(this, actionManager) || this;
  48813. _this.propertyPath = propertyPath;
  48814. _this.value = value;
  48815. _this.operator = operator;
  48816. _this._target = target;
  48817. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48818. _this._property = _this._getProperty(_this.propertyPath);
  48819. return _this;
  48820. }
  48821. Object.defineProperty(ValueCondition, "IsEqual", {
  48822. /**
  48823. * returns the number for IsEqual
  48824. */
  48825. get: function () {
  48826. return ValueCondition._IsEqual;
  48827. },
  48828. enumerable: true,
  48829. configurable: true
  48830. });
  48831. Object.defineProperty(ValueCondition, "IsDifferent", {
  48832. /**
  48833. * Returns the number for IsDifferent
  48834. */
  48835. get: function () {
  48836. return ValueCondition._IsDifferent;
  48837. },
  48838. enumerable: true,
  48839. configurable: true
  48840. });
  48841. Object.defineProperty(ValueCondition, "IsGreater", {
  48842. /**
  48843. * Returns the number for IsGreater
  48844. */
  48845. get: function () {
  48846. return ValueCondition._IsGreater;
  48847. },
  48848. enumerable: true,
  48849. configurable: true
  48850. });
  48851. Object.defineProperty(ValueCondition, "IsLesser", {
  48852. /**
  48853. * Returns the number for IsLesser
  48854. */
  48855. get: function () {
  48856. return ValueCondition._IsLesser;
  48857. },
  48858. enumerable: true,
  48859. configurable: true
  48860. });
  48861. /**
  48862. * Compares the given value with the property value for the specified conditional operator
  48863. * @returns the result of the comparison
  48864. */
  48865. ValueCondition.prototype.isValid = function () {
  48866. switch (this.operator) {
  48867. case ValueCondition.IsGreater:
  48868. return this._effectiveTarget[this._property] > this.value;
  48869. case ValueCondition.IsLesser:
  48870. return this._effectiveTarget[this._property] < this.value;
  48871. case ValueCondition.IsEqual:
  48872. case ValueCondition.IsDifferent:
  48873. var check;
  48874. if (this.value.equals) {
  48875. check = this.value.equals(this._effectiveTarget[this._property]);
  48876. }
  48877. else {
  48878. check = this.value === this._effectiveTarget[this._property];
  48879. }
  48880. return this.operator === ValueCondition.IsEqual ? check : !check;
  48881. }
  48882. return false;
  48883. };
  48884. /**
  48885. * Serialize the ValueCondition into a JSON compatible object
  48886. * @returns serialization object
  48887. */
  48888. ValueCondition.prototype.serialize = function () {
  48889. return this._serialize({
  48890. name: "ValueCondition",
  48891. properties: [
  48892. BABYLON.Action._GetTargetProperty(this._target),
  48893. { name: "propertyPath", value: this.propertyPath },
  48894. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48895. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48896. ]
  48897. });
  48898. };
  48899. /**
  48900. * Gets the name of the conditional operator for the ValueCondition
  48901. * @param operator the conditional operator
  48902. * @returns the name
  48903. */
  48904. ValueCondition.GetOperatorName = function (operator) {
  48905. switch (operator) {
  48906. case ValueCondition._IsEqual: return "IsEqual";
  48907. case ValueCondition._IsDifferent: return "IsDifferent";
  48908. case ValueCondition._IsGreater: return "IsGreater";
  48909. case ValueCondition._IsLesser: return "IsLesser";
  48910. default: return "";
  48911. }
  48912. };
  48913. /**
  48914. * Internal only
  48915. * @ignore
  48916. */
  48917. ValueCondition._IsEqual = 0;
  48918. /**
  48919. * Internal only
  48920. * @ignore
  48921. */
  48922. ValueCondition._IsDifferent = 1;
  48923. /**
  48924. * Internal only
  48925. * @ignore
  48926. */
  48927. ValueCondition._IsGreater = 2;
  48928. /**
  48929. * Internal only
  48930. * @ignore
  48931. */
  48932. ValueCondition._IsLesser = 3;
  48933. return ValueCondition;
  48934. }(Condition));
  48935. BABYLON.ValueCondition = ValueCondition;
  48936. /**
  48937. * Defines a predicate condition as an extension of Condition
  48938. */
  48939. var PredicateCondition = /** @class */ (function (_super) {
  48940. __extends(PredicateCondition, _super);
  48941. /**
  48942. * Creates a new {BABYLON.PredicateCondition}
  48943. * @param actionManager manager for the action the condition applies to
  48944. * @param predicate
  48945. */
  48946. function PredicateCondition(actionManager, predicate) {
  48947. var _this = _super.call(this, actionManager) || this;
  48948. _this.predicate = predicate;
  48949. return _this;
  48950. }
  48951. /**
  48952. * @returns the validity of the predicate condition
  48953. */
  48954. PredicateCondition.prototype.isValid = function () {
  48955. return this.predicate();
  48956. };
  48957. return PredicateCondition;
  48958. }(Condition));
  48959. BABYLON.PredicateCondition = PredicateCondition;
  48960. /**
  48961. * Defines a state condition as an extension of {BABYLON.Condition}
  48962. */
  48963. var StateCondition = /** @class */ (function (_super) {
  48964. __extends(StateCondition, _super);
  48965. /**
  48966. * Creates a new {BABYLON.StateCondition}
  48967. * @param actionManager manager for the action the condition applies to
  48968. * @param target of the condition
  48969. * @param value to compare with target state
  48970. */
  48971. function StateCondition(actionManager, target, value) {
  48972. var _this = _super.call(this, actionManager) || this;
  48973. _this.value = value;
  48974. _this._target = target;
  48975. return _this;
  48976. }
  48977. /**
  48978. * @returns the validity of the state
  48979. */
  48980. StateCondition.prototype.isValid = function () {
  48981. return this._target.state === this.value;
  48982. };
  48983. /**
  48984. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  48985. * @returns serialization object
  48986. */
  48987. StateCondition.prototype.serialize = function () {
  48988. return this._serialize({
  48989. name: "StateCondition",
  48990. properties: [
  48991. BABYLON.Action._GetTargetProperty(this._target),
  48992. { name: "value", value: this.value }
  48993. ]
  48994. });
  48995. };
  48996. return StateCondition;
  48997. }(Condition));
  48998. BABYLON.StateCondition = StateCondition;
  48999. })(BABYLON || (BABYLON = {}));
  49000. //# sourceMappingURL=babylon.condition.js.map
  49001. "use strict";
  49002. var BABYLON;
  49003. (function (BABYLON) {
  49004. /**
  49005. * The action to be carried out following a trigger
  49006. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  49007. */
  49008. var Action = /** @class */ (function () {
  49009. /**
  49010. * Creates a new Action
  49011. * @param triggerOptions the trigger, with or without parameters, for the action
  49012. * @param condition an optional determinant of action
  49013. */
  49014. function Action(triggerOptions, condition) {
  49015. this.triggerOptions = triggerOptions;
  49016. /**
  49017. * An event triggered prior to action being executed.
  49018. * @type Observable
  49019. */
  49020. this.onBeforeExecuteObservable = new BABYLON.Observable();
  49021. if (triggerOptions.parameter) {
  49022. this.trigger = triggerOptions.trigger;
  49023. this._triggerParameter = triggerOptions.parameter;
  49024. }
  49025. else {
  49026. this.trigger = triggerOptions;
  49027. }
  49028. this._nextActiveAction = this;
  49029. this._condition = condition;
  49030. }
  49031. /**
  49032. * Internal only
  49033. * @ignore
  49034. */
  49035. Action.prototype._prepare = function () {
  49036. };
  49037. /**
  49038. * Gets the trigger parameters
  49039. * @returns the trigger parameters
  49040. */
  49041. Action.prototype.getTriggerParameter = function () {
  49042. return this._triggerParameter;
  49043. };
  49044. /**
  49045. * Internal only - executes current action event
  49046. * @ignore
  49047. */
  49048. Action.prototype._executeCurrent = function (evt) {
  49049. if (this._nextActiveAction._condition) {
  49050. var condition = this._nextActiveAction._condition;
  49051. var currentRenderId = this._actionManager.getScene().getRenderId();
  49052. // We cache the current evaluation for the current frame
  49053. if (condition._evaluationId === currentRenderId) {
  49054. if (!condition._currentResult) {
  49055. return;
  49056. }
  49057. }
  49058. else {
  49059. condition._evaluationId = currentRenderId;
  49060. if (!condition.isValid()) {
  49061. condition._currentResult = false;
  49062. return;
  49063. }
  49064. condition._currentResult = true;
  49065. }
  49066. }
  49067. this.onBeforeExecuteObservable.notifyObservers(this);
  49068. this._nextActiveAction.execute(evt);
  49069. this.skipToNextActiveAction();
  49070. };
  49071. /**
  49072. * Execute placeholder for child classes
  49073. * @param evt optional action event
  49074. */
  49075. Action.prototype.execute = function (evt) {
  49076. };
  49077. /**
  49078. * Skips to next active action
  49079. */
  49080. Action.prototype.skipToNextActiveAction = function () {
  49081. if (this._nextActiveAction._child) {
  49082. if (!this._nextActiveAction._child._actionManager) {
  49083. this._nextActiveAction._child._actionManager = this._actionManager;
  49084. }
  49085. this._nextActiveAction = this._nextActiveAction._child;
  49086. }
  49087. else {
  49088. this._nextActiveAction = this;
  49089. }
  49090. };
  49091. /**
  49092. * Adds action to chain of actions, may be a DoNothingAction
  49093. * @param index The index of the attribute.
  49094. * @returns The action passed in
  49095. * @see https://www.babylonjs-playground.com/#1T30HR#0
  49096. */
  49097. Action.prototype.then = function (action) {
  49098. this._child = action;
  49099. action._actionManager = this._actionManager;
  49100. action._prepare();
  49101. return action;
  49102. };
  49103. /**
  49104. * Internal only
  49105. * @ignore
  49106. */
  49107. Action.prototype._getProperty = function (propertyPath) {
  49108. return this._actionManager._getProperty(propertyPath);
  49109. };
  49110. /**
  49111. * Internal only
  49112. * @ignore
  49113. */
  49114. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  49115. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49116. };
  49117. /**
  49118. * Serialize placeholder for child classes
  49119. * @param parent of child
  49120. * @returns the serialized object
  49121. */
  49122. Action.prototype.serialize = function (parent) {
  49123. };
  49124. /**
  49125. * Internal only called by serialize
  49126. * @ignore
  49127. */
  49128. Action.prototype._serialize = function (serializedAction, parent) {
  49129. var serializationObject = {
  49130. type: 1,
  49131. children: [],
  49132. name: serializedAction.name,
  49133. properties: serializedAction.properties || []
  49134. };
  49135. // Serialize child
  49136. if (this._child) {
  49137. this._child.serialize(serializationObject);
  49138. }
  49139. // Check if "this" has a condition
  49140. if (this._condition) {
  49141. var serializedCondition = this._condition.serialize();
  49142. serializedCondition.children.push(serializationObject);
  49143. if (parent) {
  49144. parent.children.push(serializedCondition);
  49145. }
  49146. return serializedCondition;
  49147. }
  49148. if (parent) {
  49149. parent.children.push(serializationObject);
  49150. }
  49151. return serializationObject;
  49152. };
  49153. /**
  49154. * Internal only
  49155. * @ignore
  49156. */
  49157. Action._SerializeValueAsString = function (value) {
  49158. if (typeof value === "number") {
  49159. return value.toString();
  49160. }
  49161. if (typeof value === "boolean") {
  49162. return value ? "true" : "false";
  49163. }
  49164. if (value instanceof BABYLON.Vector2) {
  49165. return value.x + ", " + value.y;
  49166. }
  49167. if (value instanceof BABYLON.Vector3) {
  49168. return value.x + ", " + value.y + ", " + value.z;
  49169. }
  49170. if (value instanceof BABYLON.Color3) {
  49171. return value.r + ", " + value.g + ", " + value.b;
  49172. }
  49173. if (value instanceof BABYLON.Color4) {
  49174. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  49175. }
  49176. return value; // string
  49177. };
  49178. /**
  49179. * Internal only
  49180. * @ignore
  49181. */
  49182. Action._GetTargetProperty = function (target) {
  49183. return {
  49184. name: "target",
  49185. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  49186. : target instanceof BABYLON.Light ? "LightProperties"
  49187. : target instanceof BABYLON.Camera ? "CameraProperties"
  49188. : "SceneProperties",
  49189. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  49190. };
  49191. };
  49192. return Action;
  49193. }());
  49194. BABYLON.Action = Action;
  49195. })(BABYLON || (BABYLON = {}));
  49196. //# sourceMappingURL=babylon.action.js.map
  49197. "use strict";
  49198. var BABYLON;
  49199. (function (BABYLON) {
  49200. /**
  49201. * ActionEvent is the event being sent when an action is triggered.
  49202. */
  49203. var ActionEvent = /** @class */ (function () {
  49204. /**
  49205. * @param source The mesh or sprite that triggered the action.
  49206. * @param pointerX The X mouse cursor position at the time of the event
  49207. * @param pointerY The Y mouse cursor position at the time of the event
  49208. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  49209. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  49210. */
  49211. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49212. this.source = source;
  49213. this.pointerX = pointerX;
  49214. this.pointerY = pointerY;
  49215. this.meshUnderPointer = meshUnderPointer;
  49216. this.sourceEvent = sourceEvent;
  49217. this.additionalData = additionalData;
  49218. }
  49219. /**
  49220. * Helper function to auto-create an ActionEvent from a source mesh.
  49221. * @param source The source mesh that triggered the event
  49222. * @param evt {Event} The original (browser) event
  49223. */
  49224. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49225. var scene = source.getScene();
  49226. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49227. };
  49228. /**
  49229. * Helper function to auto-create an ActionEvent from a source mesh.
  49230. * @param source The source sprite that triggered the event
  49231. * @param scene Scene associated with the sprite
  49232. * @param evt {Event} The original (browser) event
  49233. */
  49234. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49235. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49236. };
  49237. /**
  49238. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49239. * @param scene the scene where the event occurred
  49240. * @param evt {Event} The original (browser) event
  49241. */
  49242. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49243. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49244. };
  49245. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49246. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49247. };
  49248. return ActionEvent;
  49249. }());
  49250. BABYLON.ActionEvent = ActionEvent;
  49251. /**
  49252. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49253. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49254. */
  49255. var ActionManager = /** @class */ (function () {
  49256. function ActionManager(scene) {
  49257. // Members
  49258. this.actions = new Array();
  49259. this.hoverCursor = '';
  49260. this._scene = scene;
  49261. scene._actionManagers.push(this);
  49262. }
  49263. Object.defineProperty(ActionManager, "NothingTrigger", {
  49264. get: function () {
  49265. return ActionManager._NothingTrigger;
  49266. },
  49267. enumerable: true,
  49268. configurable: true
  49269. });
  49270. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49271. get: function () {
  49272. return ActionManager._OnPickTrigger;
  49273. },
  49274. enumerable: true,
  49275. configurable: true
  49276. });
  49277. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49278. get: function () {
  49279. return ActionManager._OnLeftPickTrigger;
  49280. },
  49281. enumerable: true,
  49282. configurable: true
  49283. });
  49284. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49285. get: function () {
  49286. return ActionManager._OnRightPickTrigger;
  49287. },
  49288. enumerable: true,
  49289. configurable: true
  49290. });
  49291. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49292. get: function () {
  49293. return ActionManager._OnCenterPickTrigger;
  49294. },
  49295. enumerable: true,
  49296. configurable: true
  49297. });
  49298. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49299. get: function () {
  49300. return ActionManager._OnPickDownTrigger;
  49301. },
  49302. enumerable: true,
  49303. configurable: true
  49304. });
  49305. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49306. get: function () {
  49307. return ActionManager._OnDoublePickTrigger;
  49308. },
  49309. enumerable: true,
  49310. configurable: true
  49311. });
  49312. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49313. get: function () {
  49314. return ActionManager._OnPickUpTrigger;
  49315. },
  49316. enumerable: true,
  49317. configurable: true
  49318. });
  49319. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49320. /// This trigger will only be raised if you also declared a OnPickDown
  49321. get: function () {
  49322. return ActionManager._OnPickOutTrigger;
  49323. },
  49324. enumerable: true,
  49325. configurable: true
  49326. });
  49327. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49328. get: function () {
  49329. return ActionManager._OnLongPressTrigger;
  49330. },
  49331. enumerable: true,
  49332. configurable: true
  49333. });
  49334. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49335. get: function () {
  49336. return ActionManager._OnPointerOverTrigger;
  49337. },
  49338. enumerable: true,
  49339. configurable: true
  49340. });
  49341. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49342. get: function () {
  49343. return ActionManager._OnPointerOutTrigger;
  49344. },
  49345. enumerable: true,
  49346. configurable: true
  49347. });
  49348. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49349. get: function () {
  49350. return ActionManager._OnEveryFrameTrigger;
  49351. },
  49352. enumerable: true,
  49353. configurable: true
  49354. });
  49355. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49356. get: function () {
  49357. return ActionManager._OnIntersectionEnterTrigger;
  49358. },
  49359. enumerable: true,
  49360. configurable: true
  49361. });
  49362. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49363. get: function () {
  49364. return ActionManager._OnIntersectionExitTrigger;
  49365. },
  49366. enumerable: true,
  49367. configurable: true
  49368. });
  49369. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49370. get: function () {
  49371. return ActionManager._OnKeyDownTrigger;
  49372. },
  49373. enumerable: true,
  49374. configurable: true
  49375. });
  49376. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49377. get: function () {
  49378. return ActionManager._OnKeyUpTrigger;
  49379. },
  49380. enumerable: true,
  49381. configurable: true
  49382. });
  49383. // Methods
  49384. ActionManager.prototype.dispose = function () {
  49385. var index = this._scene._actionManagers.indexOf(this);
  49386. for (var i = 0; i < this.actions.length; i++) {
  49387. var action = this.actions[i];
  49388. ActionManager.Triggers[action.trigger]--;
  49389. if (ActionManager.Triggers[action.trigger] === 0) {
  49390. delete ActionManager.Triggers[action.trigger];
  49391. }
  49392. }
  49393. if (index > -1) {
  49394. this._scene._actionManagers.splice(index, 1);
  49395. }
  49396. };
  49397. ActionManager.prototype.getScene = function () {
  49398. return this._scene;
  49399. };
  49400. /**
  49401. * Does this action manager handles actions of any of the given triggers
  49402. * @param {number[]} triggers - the triggers to be tested
  49403. * @return {boolean} whether one (or more) of the triggers is handeled
  49404. */
  49405. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49406. for (var index = 0; index < this.actions.length; index++) {
  49407. var action = this.actions[index];
  49408. if (triggers.indexOf(action.trigger) > -1) {
  49409. return true;
  49410. }
  49411. }
  49412. return false;
  49413. };
  49414. /**
  49415. * Does this action manager handles actions of a given trigger
  49416. * @param {number} trigger - the trigger to be tested
  49417. * @return {boolean} whether the trigger is handeled
  49418. */
  49419. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49420. for (var index = 0; index < this.actions.length; index++) {
  49421. var action = this.actions[index];
  49422. if (action.trigger === trigger) {
  49423. return true;
  49424. }
  49425. }
  49426. return false;
  49427. };
  49428. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49429. /**
  49430. * Does this action manager has pointer triggers
  49431. * @return {boolean} whether or not it has pointer triggers
  49432. */
  49433. get: function () {
  49434. for (var index = 0; index < this.actions.length; index++) {
  49435. var action = this.actions[index];
  49436. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49437. return true;
  49438. }
  49439. }
  49440. return false;
  49441. },
  49442. enumerable: true,
  49443. configurable: true
  49444. });
  49445. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49446. /**
  49447. * Does this action manager has pick triggers
  49448. * @return {boolean} whether or not it has pick triggers
  49449. */
  49450. get: function () {
  49451. for (var index = 0; index < this.actions.length; index++) {
  49452. var action = this.actions[index];
  49453. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49454. return true;
  49455. }
  49456. }
  49457. return false;
  49458. },
  49459. enumerable: true,
  49460. configurable: true
  49461. });
  49462. Object.defineProperty(ActionManager, "HasTriggers", {
  49463. /**
  49464. * Does exist one action manager with at least one trigger
  49465. * @return {boolean} whether or not it exists one action manager with one trigger
  49466. **/
  49467. get: function () {
  49468. for (var t in ActionManager.Triggers) {
  49469. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49470. return true;
  49471. }
  49472. }
  49473. return false;
  49474. },
  49475. enumerable: true,
  49476. configurable: true
  49477. });
  49478. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49479. /**
  49480. * Does exist one action manager with at least one pick trigger
  49481. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49482. **/
  49483. get: function () {
  49484. for (var t in ActionManager.Triggers) {
  49485. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49486. var t_int = parseInt(t);
  49487. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49488. return true;
  49489. }
  49490. }
  49491. }
  49492. return false;
  49493. },
  49494. enumerable: true,
  49495. configurable: true
  49496. });
  49497. /**
  49498. * Does exist one action manager that handles actions of a given trigger
  49499. * @param {number} trigger - the trigger to be tested
  49500. * @return {boolean} whether the trigger is handeled by at least one action manager
  49501. **/
  49502. ActionManager.HasSpecificTrigger = function (trigger) {
  49503. for (var t in ActionManager.Triggers) {
  49504. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49505. var t_int = parseInt(t);
  49506. if (t_int === trigger) {
  49507. return true;
  49508. }
  49509. }
  49510. }
  49511. return false;
  49512. };
  49513. /**
  49514. * Registers an action to this action manager
  49515. * @param {BABYLON.Action} action - the action to be registered
  49516. * @return {BABYLON.Action} the action amended (prepared) after registration
  49517. */
  49518. ActionManager.prototype.registerAction = function (action) {
  49519. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49520. if (this.getScene().actionManager !== this) {
  49521. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49522. return null;
  49523. }
  49524. }
  49525. this.actions.push(action);
  49526. if (ActionManager.Triggers[action.trigger]) {
  49527. ActionManager.Triggers[action.trigger]++;
  49528. }
  49529. else {
  49530. ActionManager.Triggers[action.trigger] = 1;
  49531. }
  49532. action._actionManager = this;
  49533. action._prepare();
  49534. return action;
  49535. };
  49536. /**
  49537. * Unregisters an action to this action manager
  49538. * @param action The action to be unregistered
  49539. * @return whether the action has been unregistered
  49540. */
  49541. ActionManager.prototype.unregisterAction = function (action) {
  49542. var index = this.actions.indexOf(action);
  49543. if (index !== -1) {
  49544. this.actions.splice(index, 1);
  49545. ActionManager.Triggers[action.trigger] -= 1;
  49546. if (ActionManager.Triggers[action.trigger] === 0) {
  49547. delete ActionManager.Triggers[action.trigger];
  49548. }
  49549. delete action._actionManager;
  49550. return true;
  49551. }
  49552. return false;
  49553. };
  49554. /**
  49555. * Process a specific trigger
  49556. * @param {number} trigger - the trigger to process
  49557. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49558. */
  49559. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49560. for (var index = 0; index < this.actions.length; index++) {
  49561. var action = this.actions[index];
  49562. if (action.trigger === trigger) {
  49563. if (evt) {
  49564. if (trigger === ActionManager.OnKeyUpTrigger
  49565. || trigger === ActionManager.OnKeyDownTrigger) {
  49566. var parameter = action.getTriggerParameter();
  49567. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49568. if (!parameter.toLowerCase) {
  49569. continue;
  49570. }
  49571. var lowerCase = parameter.toLowerCase();
  49572. if (lowerCase !== evt.sourceEvent.key) {
  49573. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49574. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49575. if (actualkey !== lowerCase) {
  49576. continue;
  49577. }
  49578. }
  49579. }
  49580. }
  49581. }
  49582. action._executeCurrent(evt);
  49583. }
  49584. }
  49585. };
  49586. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49587. var properties = propertyPath.split(".");
  49588. for (var index = 0; index < properties.length - 1; index++) {
  49589. target = target[properties[index]];
  49590. }
  49591. return target;
  49592. };
  49593. ActionManager.prototype._getProperty = function (propertyPath) {
  49594. var properties = propertyPath.split(".");
  49595. return properties[properties.length - 1];
  49596. };
  49597. ActionManager.prototype.serialize = function (name) {
  49598. var root = {
  49599. children: new Array(),
  49600. name: name,
  49601. type: 3,
  49602. properties: new Array() // Empty for root but required
  49603. };
  49604. for (var i = 0; i < this.actions.length; i++) {
  49605. var triggerObject = {
  49606. type: 0,
  49607. children: new Array(),
  49608. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49609. properties: new Array()
  49610. };
  49611. var triggerOptions = this.actions[i].triggerOptions;
  49612. if (triggerOptions && typeof triggerOptions !== "number") {
  49613. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49614. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49615. }
  49616. else {
  49617. var parameter = {};
  49618. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49619. if (triggerOptions.parameter.mesh) {
  49620. parameter._meshId = triggerOptions.parameter.mesh.id;
  49621. }
  49622. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49623. }
  49624. }
  49625. // Serialize child action, recursively
  49626. this.actions[i].serialize(triggerObject);
  49627. // Add serialized trigger
  49628. root.children.push(triggerObject);
  49629. }
  49630. return root;
  49631. };
  49632. ActionManager.Parse = function (parsedActions, object, scene) {
  49633. var actionManager = new ActionManager(scene);
  49634. if (object === null)
  49635. scene.actionManager = actionManager;
  49636. else
  49637. object.actionManager = actionManager;
  49638. // instanciate a new object
  49639. var instanciate = function (name, params) {
  49640. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49641. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49642. newInstance.constructor.apply(newInstance, params);
  49643. return newInstance;
  49644. };
  49645. var parseParameter = function (name, value, target, propertyPath) {
  49646. if (propertyPath === null) {
  49647. // String, boolean or float
  49648. var floatValue = parseFloat(value);
  49649. if (value === "true" || value === "false")
  49650. return value === "true";
  49651. else
  49652. return isNaN(floatValue) ? value : floatValue;
  49653. }
  49654. var effectiveTarget = propertyPath.split(".");
  49655. var values = value.split(",");
  49656. // Get effective Target
  49657. for (var i = 0; i < effectiveTarget.length; i++) {
  49658. target = target[effectiveTarget[i]];
  49659. }
  49660. // Return appropriate value with its type
  49661. if (typeof (target) === "boolean")
  49662. return values[0] === "true";
  49663. if (typeof (target) === "string")
  49664. return values[0];
  49665. // Parameters with multiple values such as Vector3 etc.
  49666. var split = new Array();
  49667. for (var i = 0; i < values.length; i++)
  49668. split.push(parseFloat(values[i]));
  49669. if (target instanceof BABYLON.Vector3)
  49670. return BABYLON.Vector3.FromArray(split);
  49671. if (target instanceof BABYLON.Vector4)
  49672. return BABYLON.Vector4.FromArray(split);
  49673. if (target instanceof BABYLON.Color3)
  49674. return BABYLON.Color3.FromArray(split);
  49675. if (target instanceof BABYLON.Color4)
  49676. return BABYLON.Color4.FromArray(split);
  49677. return parseFloat(values[0]);
  49678. };
  49679. // traverse graph per trigger
  49680. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49681. if (combineArray === void 0) { combineArray = null; }
  49682. if (parsedAction.detached)
  49683. return;
  49684. var parameters = new Array();
  49685. var target = null;
  49686. var propertyPath = null;
  49687. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49688. // Parameters
  49689. if (parsedAction.type === 2)
  49690. parameters.push(actionManager);
  49691. else
  49692. parameters.push(trigger);
  49693. if (combine) {
  49694. var actions = new Array();
  49695. for (var j = 0; j < parsedAction.combine.length; j++) {
  49696. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49697. }
  49698. parameters.push(actions);
  49699. }
  49700. else {
  49701. for (var i = 0; i < parsedAction.properties.length; i++) {
  49702. var value = parsedAction.properties[i].value;
  49703. var name = parsedAction.properties[i].name;
  49704. var targetType = parsedAction.properties[i].targetType;
  49705. if (name === "target")
  49706. if (targetType !== null && targetType === "SceneProperties")
  49707. value = target = scene;
  49708. else
  49709. value = target = scene.getNodeByName(value);
  49710. else if (name === "parent")
  49711. value = scene.getNodeByName(value);
  49712. else if (name === "sound")
  49713. value = scene.getSoundByName(value);
  49714. else if (name !== "propertyPath") {
  49715. if (parsedAction.type === 2 && name === "operator")
  49716. value = BABYLON.ValueCondition[value];
  49717. else
  49718. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49719. }
  49720. else {
  49721. propertyPath = value;
  49722. }
  49723. parameters.push(value);
  49724. }
  49725. }
  49726. if (combineArray === null) {
  49727. parameters.push(condition);
  49728. }
  49729. else {
  49730. parameters.push(null);
  49731. }
  49732. // If interpolate value action
  49733. if (parsedAction.name === "InterpolateValueAction") {
  49734. var param = parameters[parameters.length - 2];
  49735. parameters[parameters.length - 1] = param;
  49736. parameters[parameters.length - 2] = condition;
  49737. }
  49738. // Action or condition(s) and not CombineAction
  49739. var newAction = instanciate(parsedAction.name, parameters);
  49740. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49741. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49742. if (action)
  49743. action.then(nothing);
  49744. else
  49745. actionManager.registerAction(nothing);
  49746. action = nothing;
  49747. }
  49748. if (combineArray === null) {
  49749. if (newAction instanceof BABYLON.Condition) {
  49750. condition = newAction;
  49751. newAction = action;
  49752. }
  49753. else {
  49754. condition = null;
  49755. if (action)
  49756. action.then(newAction);
  49757. else
  49758. actionManager.registerAction(newAction);
  49759. }
  49760. }
  49761. else {
  49762. combineArray.push(newAction);
  49763. }
  49764. for (var i = 0; i < parsedAction.children.length; i++)
  49765. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49766. };
  49767. // triggers
  49768. for (var i = 0; i < parsedActions.children.length; i++) {
  49769. var triggerParams;
  49770. var trigger = parsedActions.children[i];
  49771. if (trigger.properties.length > 0) {
  49772. var param = trigger.properties[0].value;
  49773. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49774. if (value._meshId) {
  49775. value.mesh = scene.getMeshByID(value._meshId);
  49776. }
  49777. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49778. }
  49779. else
  49780. triggerParams = ActionManager[trigger.name];
  49781. for (var j = 0; j < trigger.children.length; j++) {
  49782. if (!trigger.detached)
  49783. traverse(trigger.children[j], triggerParams, null, null);
  49784. }
  49785. }
  49786. };
  49787. ActionManager.GetTriggerName = function (trigger) {
  49788. switch (trigger) {
  49789. case 0: return "NothingTrigger";
  49790. case 1: return "OnPickTrigger";
  49791. case 2: return "OnLeftPickTrigger";
  49792. case 3: return "OnRightPickTrigger";
  49793. case 4: return "OnCenterPickTrigger";
  49794. case 5: return "OnPickDownTrigger";
  49795. case 6: return "OnPickUpTrigger";
  49796. case 7: return "OnLongPressTrigger";
  49797. case 8: return "OnPointerOverTrigger";
  49798. case 9: return "OnPointerOutTrigger";
  49799. case 10: return "OnEveryFrameTrigger";
  49800. case 11: return "OnIntersectionEnterTrigger";
  49801. case 12: return "OnIntersectionExitTrigger";
  49802. case 13: return "OnKeyDownTrigger";
  49803. case 14: return "OnKeyUpTrigger";
  49804. case 15: return "OnPickOutTrigger";
  49805. default: return "";
  49806. }
  49807. };
  49808. // Statics
  49809. ActionManager._NothingTrigger = 0;
  49810. ActionManager._OnPickTrigger = 1;
  49811. ActionManager._OnLeftPickTrigger = 2;
  49812. ActionManager._OnRightPickTrigger = 3;
  49813. ActionManager._OnCenterPickTrigger = 4;
  49814. ActionManager._OnPickDownTrigger = 5;
  49815. ActionManager._OnDoublePickTrigger = 6;
  49816. ActionManager._OnPickUpTrigger = 7;
  49817. ActionManager._OnLongPressTrigger = 8;
  49818. ActionManager._OnPointerOverTrigger = 9;
  49819. ActionManager._OnPointerOutTrigger = 10;
  49820. ActionManager._OnEveryFrameTrigger = 11;
  49821. ActionManager._OnIntersectionEnterTrigger = 12;
  49822. ActionManager._OnIntersectionExitTrigger = 13;
  49823. ActionManager._OnKeyDownTrigger = 14;
  49824. ActionManager._OnKeyUpTrigger = 15;
  49825. ActionManager._OnPickOutTrigger = 16;
  49826. ActionManager.Triggers = {};
  49827. return ActionManager;
  49828. }());
  49829. BABYLON.ActionManager = ActionManager;
  49830. })(BABYLON || (BABYLON = {}));
  49831. //# sourceMappingURL=babylon.actionManager.js.map
  49832. "use strict";
  49833. var BABYLON;
  49834. (function (BABYLON) {
  49835. var InterpolateValueAction = /** @class */ (function (_super) {
  49836. __extends(InterpolateValueAction, _super);
  49837. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49838. if (duration === void 0) { duration = 1000; }
  49839. var _this = _super.call(this, triggerOptions, condition) || this;
  49840. _this.propertyPath = propertyPath;
  49841. _this.value = value;
  49842. _this.duration = duration;
  49843. _this.stopOtherAnimations = stopOtherAnimations;
  49844. _this.onInterpolationDone = onInterpolationDone;
  49845. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49846. _this._target = _this._effectiveTarget = target;
  49847. return _this;
  49848. }
  49849. InterpolateValueAction.prototype._prepare = function () {
  49850. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49851. this._property = this._getProperty(this.propertyPath);
  49852. };
  49853. InterpolateValueAction.prototype.execute = function () {
  49854. var _this = this;
  49855. var scene = this._actionManager.getScene();
  49856. var keys = [
  49857. {
  49858. frame: 0,
  49859. value: this._effectiveTarget[this._property]
  49860. }, {
  49861. frame: 100,
  49862. value: this.value
  49863. }
  49864. ];
  49865. var dataType;
  49866. if (typeof this.value === "number") {
  49867. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49868. }
  49869. else if (this.value instanceof BABYLON.Color3) {
  49870. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49871. }
  49872. else if (this.value instanceof BABYLON.Vector3) {
  49873. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49874. }
  49875. else if (this.value instanceof BABYLON.Matrix) {
  49876. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49877. }
  49878. else if (this.value instanceof BABYLON.Quaternion) {
  49879. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49880. }
  49881. else {
  49882. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49883. return;
  49884. }
  49885. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49886. animation.setKeys(keys);
  49887. if (this.stopOtherAnimations) {
  49888. scene.stopAnimation(this._effectiveTarget);
  49889. }
  49890. var wrapper = function () {
  49891. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49892. if (_this.onInterpolationDone) {
  49893. _this.onInterpolationDone();
  49894. }
  49895. };
  49896. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49897. };
  49898. InterpolateValueAction.prototype.serialize = function (parent) {
  49899. return _super.prototype._serialize.call(this, {
  49900. name: "InterpolateValueAction",
  49901. properties: [
  49902. BABYLON.Action._GetTargetProperty(this._target),
  49903. { name: "propertyPath", value: this.propertyPath },
  49904. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49905. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49906. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49907. ]
  49908. }, parent);
  49909. };
  49910. return InterpolateValueAction;
  49911. }(BABYLON.Action));
  49912. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49913. })(BABYLON || (BABYLON = {}));
  49914. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49915. "use strict";
  49916. var BABYLON;
  49917. (function (BABYLON) {
  49918. var SwitchBooleanAction = /** @class */ (function (_super) {
  49919. __extends(SwitchBooleanAction, _super);
  49920. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49921. var _this = _super.call(this, triggerOptions, condition) || this;
  49922. _this.propertyPath = propertyPath;
  49923. _this._target = _this._effectiveTarget = target;
  49924. return _this;
  49925. }
  49926. SwitchBooleanAction.prototype._prepare = function () {
  49927. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49928. this._property = this._getProperty(this.propertyPath);
  49929. };
  49930. SwitchBooleanAction.prototype.execute = function () {
  49931. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49932. };
  49933. SwitchBooleanAction.prototype.serialize = function (parent) {
  49934. return _super.prototype._serialize.call(this, {
  49935. name: "SwitchBooleanAction",
  49936. properties: [
  49937. BABYLON.Action._GetTargetProperty(this._target),
  49938. { name: "propertyPath", value: this.propertyPath }
  49939. ]
  49940. }, parent);
  49941. };
  49942. return SwitchBooleanAction;
  49943. }(BABYLON.Action));
  49944. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49945. var SetStateAction = /** @class */ (function (_super) {
  49946. __extends(SetStateAction, _super);
  49947. function SetStateAction(triggerOptions, target, value, condition) {
  49948. var _this = _super.call(this, triggerOptions, condition) || this;
  49949. _this.value = value;
  49950. _this._target = target;
  49951. return _this;
  49952. }
  49953. SetStateAction.prototype.execute = function () {
  49954. this._target.state = this.value;
  49955. };
  49956. SetStateAction.prototype.serialize = function (parent) {
  49957. return _super.prototype._serialize.call(this, {
  49958. name: "SetStateAction",
  49959. properties: [
  49960. BABYLON.Action._GetTargetProperty(this._target),
  49961. { name: "value", value: this.value }
  49962. ]
  49963. }, parent);
  49964. };
  49965. return SetStateAction;
  49966. }(BABYLON.Action));
  49967. BABYLON.SetStateAction = SetStateAction;
  49968. var SetValueAction = /** @class */ (function (_super) {
  49969. __extends(SetValueAction, _super);
  49970. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49971. var _this = _super.call(this, triggerOptions, condition) || this;
  49972. _this.propertyPath = propertyPath;
  49973. _this.value = value;
  49974. _this._target = _this._effectiveTarget = target;
  49975. return _this;
  49976. }
  49977. SetValueAction.prototype._prepare = function () {
  49978. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49979. this._property = this._getProperty(this.propertyPath);
  49980. };
  49981. SetValueAction.prototype.execute = function () {
  49982. this._effectiveTarget[this._property] = this.value;
  49983. if (this._target.markAsDirty) {
  49984. this._target.markAsDirty(this._property);
  49985. }
  49986. };
  49987. SetValueAction.prototype.serialize = function (parent) {
  49988. return _super.prototype._serialize.call(this, {
  49989. name: "SetValueAction",
  49990. properties: [
  49991. BABYLON.Action._GetTargetProperty(this._target),
  49992. { name: "propertyPath", value: this.propertyPath },
  49993. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49994. ]
  49995. }, parent);
  49996. };
  49997. return SetValueAction;
  49998. }(BABYLON.Action));
  49999. BABYLON.SetValueAction = SetValueAction;
  50000. var IncrementValueAction = /** @class */ (function (_super) {
  50001. __extends(IncrementValueAction, _super);
  50002. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  50003. var _this = _super.call(this, triggerOptions, condition) || this;
  50004. _this.propertyPath = propertyPath;
  50005. _this.value = value;
  50006. _this._target = _this._effectiveTarget = target;
  50007. return _this;
  50008. }
  50009. IncrementValueAction.prototype._prepare = function () {
  50010. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50011. this._property = this._getProperty(this.propertyPath);
  50012. if (typeof this._effectiveTarget[this._property] !== "number") {
  50013. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  50014. }
  50015. };
  50016. IncrementValueAction.prototype.execute = function () {
  50017. this._effectiveTarget[this._property] += this.value;
  50018. if (this._target.markAsDirty) {
  50019. this._target.markAsDirty(this._property);
  50020. }
  50021. };
  50022. IncrementValueAction.prototype.serialize = function (parent) {
  50023. return _super.prototype._serialize.call(this, {
  50024. name: "IncrementValueAction",
  50025. properties: [
  50026. BABYLON.Action._GetTargetProperty(this._target),
  50027. { name: "propertyPath", value: this.propertyPath },
  50028. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50029. ]
  50030. }, parent);
  50031. };
  50032. return IncrementValueAction;
  50033. }(BABYLON.Action));
  50034. BABYLON.IncrementValueAction = IncrementValueAction;
  50035. var PlayAnimationAction = /** @class */ (function (_super) {
  50036. __extends(PlayAnimationAction, _super);
  50037. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  50038. var _this = _super.call(this, triggerOptions, condition) || this;
  50039. _this.from = from;
  50040. _this.to = to;
  50041. _this.loop = loop;
  50042. _this._target = target;
  50043. return _this;
  50044. }
  50045. PlayAnimationAction.prototype._prepare = function () {
  50046. };
  50047. PlayAnimationAction.prototype.execute = function () {
  50048. var scene = this._actionManager.getScene();
  50049. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  50050. };
  50051. PlayAnimationAction.prototype.serialize = function (parent) {
  50052. return _super.prototype._serialize.call(this, {
  50053. name: "PlayAnimationAction",
  50054. properties: [
  50055. BABYLON.Action._GetTargetProperty(this._target),
  50056. { name: "from", value: String(this.from) },
  50057. { name: "to", value: String(this.to) },
  50058. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  50059. ]
  50060. }, parent);
  50061. };
  50062. return PlayAnimationAction;
  50063. }(BABYLON.Action));
  50064. BABYLON.PlayAnimationAction = PlayAnimationAction;
  50065. var StopAnimationAction = /** @class */ (function (_super) {
  50066. __extends(StopAnimationAction, _super);
  50067. function StopAnimationAction(triggerOptions, target, condition) {
  50068. var _this = _super.call(this, triggerOptions, condition) || this;
  50069. _this._target = target;
  50070. return _this;
  50071. }
  50072. StopAnimationAction.prototype._prepare = function () {
  50073. };
  50074. StopAnimationAction.prototype.execute = function () {
  50075. var scene = this._actionManager.getScene();
  50076. scene.stopAnimation(this._target);
  50077. };
  50078. StopAnimationAction.prototype.serialize = function (parent) {
  50079. return _super.prototype._serialize.call(this, {
  50080. name: "StopAnimationAction",
  50081. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  50082. }, parent);
  50083. };
  50084. return StopAnimationAction;
  50085. }(BABYLON.Action));
  50086. BABYLON.StopAnimationAction = StopAnimationAction;
  50087. var DoNothingAction = /** @class */ (function (_super) {
  50088. __extends(DoNothingAction, _super);
  50089. function DoNothingAction(triggerOptions, condition) {
  50090. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  50091. return _super.call(this, triggerOptions, condition) || this;
  50092. }
  50093. DoNothingAction.prototype.execute = function () {
  50094. };
  50095. DoNothingAction.prototype.serialize = function (parent) {
  50096. return _super.prototype._serialize.call(this, {
  50097. name: "DoNothingAction",
  50098. properties: []
  50099. }, parent);
  50100. };
  50101. return DoNothingAction;
  50102. }(BABYLON.Action));
  50103. BABYLON.DoNothingAction = DoNothingAction;
  50104. var CombineAction = /** @class */ (function (_super) {
  50105. __extends(CombineAction, _super);
  50106. function CombineAction(triggerOptions, children, condition) {
  50107. var _this = _super.call(this, triggerOptions, condition) || this;
  50108. _this.children = children;
  50109. return _this;
  50110. }
  50111. CombineAction.prototype._prepare = function () {
  50112. for (var index = 0; index < this.children.length; index++) {
  50113. this.children[index]._actionManager = this._actionManager;
  50114. this.children[index]._prepare();
  50115. }
  50116. };
  50117. CombineAction.prototype.execute = function (evt) {
  50118. for (var index = 0; index < this.children.length; index++) {
  50119. this.children[index].execute(evt);
  50120. }
  50121. };
  50122. CombineAction.prototype.serialize = function (parent) {
  50123. var serializationObject = _super.prototype._serialize.call(this, {
  50124. name: "CombineAction",
  50125. properties: [],
  50126. combine: []
  50127. }, parent);
  50128. for (var i = 0; i < this.children.length; i++) {
  50129. serializationObject.combine.push(this.children[i].serialize(null));
  50130. }
  50131. return serializationObject;
  50132. };
  50133. return CombineAction;
  50134. }(BABYLON.Action));
  50135. BABYLON.CombineAction = CombineAction;
  50136. var ExecuteCodeAction = /** @class */ (function (_super) {
  50137. __extends(ExecuteCodeAction, _super);
  50138. function ExecuteCodeAction(triggerOptions, func, condition) {
  50139. var _this = _super.call(this, triggerOptions, condition) || this;
  50140. _this.func = func;
  50141. return _this;
  50142. }
  50143. ExecuteCodeAction.prototype.execute = function (evt) {
  50144. this.func(evt);
  50145. };
  50146. return ExecuteCodeAction;
  50147. }(BABYLON.Action));
  50148. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  50149. var SetParentAction = /** @class */ (function (_super) {
  50150. __extends(SetParentAction, _super);
  50151. function SetParentAction(triggerOptions, target, parent, condition) {
  50152. var _this = _super.call(this, triggerOptions, condition) || this;
  50153. _this._target = target;
  50154. _this._parent = parent;
  50155. return _this;
  50156. }
  50157. SetParentAction.prototype._prepare = function () {
  50158. };
  50159. SetParentAction.prototype.execute = function () {
  50160. if (this._target.parent === this._parent) {
  50161. return;
  50162. }
  50163. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  50164. invertParentWorldMatrix.invert();
  50165. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  50166. this._target.parent = this._parent;
  50167. };
  50168. SetParentAction.prototype.serialize = function (parent) {
  50169. return _super.prototype._serialize.call(this, {
  50170. name: "SetParentAction",
  50171. properties: [
  50172. BABYLON.Action._GetTargetProperty(this._target),
  50173. BABYLON.Action._GetTargetProperty(this._parent),
  50174. ]
  50175. }, parent);
  50176. };
  50177. return SetParentAction;
  50178. }(BABYLON.Action));
  50179. BABYLON.SetParentAction = SetParentAction;
  50180. var PlaySoundAction = /** @class */ (function (_super) {
  50181. __extends(PlaySoundAction, _super);
  50182. function PlaySoundAction(triggerOptions, sound, condition) {
  50183. var _this = _super.call(this, triggerOptions, condition) || this;
  50184. _this._sound = sound;
  50185. return _this;
  50186. }
  50187. PlaySoundAction.prototype._prepare = function () {
  50188. };
  50189. PlaySoundAction.prototype.execute = function () {
  50190. if (this._sound !== undefined)
  50191. this._sound.play();
  50192. };
  50193. PlaySoundAction.prototype.serialize = function (parent) {
  50194. return _super.prototype._serialize.call(this, {
  50195. name: "PlaySoundAction",
  50196. properties: [{ name: "sound", value: this._sound.name }]
  50197. }, parent);
  50198. };
  50199. return PlaySoundAction;
  50200. }(BABYLON.Action));
  50201. BABYLON.PlaySoundAction = PlaySoundAction;
  50202. var StopSoundAction = /** @class */ (function (_super) {
  50203. __extends(StopSoundAction, _super);
  50204. function StopSoundAction(triggerOptions, sound, condition) {
  50205. var _this = _super.call(this, triggerOptions, condition) || this;
  50206. _this._sound = sound;
  50207. return _this;
  50208. }
  50209. StopSoundAction.prototype._prepare = function () {
  50210. };
  50211. StopSoundAction.prototype.execute = function () {
  50212. if (this._sound !== undefined)
  50213. this._sound.stop();
  50214. };
  50215. StopSoundAction.prototype.serialize = function (parent) {
  50216. return _super.prototype._serialize.call(this, {
  50217. name: "StopSoundAction",
  50218. properties: [{ name: "sound", value: this._sound.name }]
  50219. }, parent);
  50220. };
  50221. return StopSoundAction;
  50222. }(BABYLON.Action));
  50223. BABYLON.StopSoundAction = StopSoundAction;
  50224. })(BABYLON || (BABYLON = {}));
  50225. //# sourceMappingURL=babylon.directActions.js.map
  50226. "use strict";
  50227. var BABYLON;
  50228. (function (BABYLON) {
  50229. var SpriteManager = /** @class */ (function () {
  50230. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50231. if (epsilon === void 0) { epsilon = 0.01; }
  50232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50233. this.name = name;
  50234. this.sprites = new Array();
  50235. this.renderingGroupId = 0;
  50236. this.layerMask = 0x0FFFFFFF;
  50237. this.fogEnabled = true;
  50238. this.isPickable = false;
  50239. /**
  50240. * An event triggered when the manager is disposed.
  50241. * @type {BABYLON.Observable}
  50242. */
  50243. this.onDisposeObservable = new BABYLON.Observable();
  50244. this._vertexBuffers = {};
  50245. this._capacity = capacity;
  50246. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50247. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50248. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50249. if (cellSize.width && cellSize.height) {
  50250. this.cellWidth = cellSize.width;
  50251. this.cellHeight = cellSize.height;
  50252. }
  50253. else if (cellSize !== undefined) {
  50254. this.cellWidth = cellSize;
  50255. this.cellHeight = cellSize;
  50256. }
  50257. else {
  50258. return;
  50259. }
  50260. this._epsilon = epsilon;
  50261. this._scene = scene;
  50262. this._scene.spriteManagers.push(this);
  50263. var indices = [];
  50264. var index = 0;
  50265. for (var count = 0; count < capacity; count++) {
  50266. indices.push(index);
  50267. indices.push(index + 1);
  50268. indices.push(index + 2);
  50269. indices.push(index);
  50270. indices.push(index + 2);
  50271. indices.push(index + 3);
  50272. index += 4;
  50273. }
  50274. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50275. // VBO
  50276. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50277. this._vertexData = new Float32Array(capacity * 16 * 4);
  50278. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50279. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50280. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50281. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50282. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50284. this._vertexBuffers["options"] = options;
  50285. this._vertexBuffers["cellInfo"] = cellInfo;
  50286. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50287. // Effects
  50288. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50289. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50290. }
  50291. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50292. set: function (callback) {
  50293. if (this._onDisposeObserver) {
  50294. this.onDisposeObservable.remove(this._onDisposeObserver);
  50295. }
  50296. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50297. },
  50298. enumerable: true,
  50299. configurable: true
  50300. });
  50301. Object.defineProperty(SpriteManager.prototype, "texture", {
  50302. get: function () {
  50303. return this._spriteTexture;
  50304. },
  50305. set: function (value) {
  50306. this._spriteTexture = value;
  50307. },
  50308. enumerable: true,
  50309. configurable: true
  50310. });
  50311. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50312. var arrayOffset = index * 16;
  50313. if (offsetX === 0)
  50314. offsetX = this._epsilon;
  50315. else if (offsetX === 1)
  50316. offsetX = 1 - this._epsilon;
  50317. if (offsetY === 0)
  50318. offsetY = this._epsilon;
  50319. else if (offsetY === 1)
  50320. offsetY = 1 - this._epsilon;
  50321. this._vertexData[arrayOffset] = sprite.position.x;
  50322. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50323. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50324. this._vertexData[arrayOffset + 3] = sprite.angle;
  50325. this._vertexData[arrayOffset + 4] = sprite.width;
  50326. this._vertexData[arrayOffset + 5] = sprite.height;
  50327. this._vertexData[arrayOffset + 6] = offsetX;
  50328. this._vertexData[arrayOffset + 7] = offsetY;
  50329. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50330. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50331. var offset = (sprite.cellIndex / rowSize) >> 0;
  50332. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50333. this._vertexData[arrayOffset + 11] = offset;
  50334. // Color
  50335. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50336. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50337. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50338. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50339. };
  50340. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50341. var count = Math.min(this._capacity, this.sprites.length);
  50342. var min = BABYLON.Vector3.Zero();
  50343. var max = BABYLON.Vector3.Zero();
  50344. var distance = Number.MAX_VALUE;
  50345. var currentSprite = null;
  50346. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50347. var cameraView = camera.getViewMatrix();
  50348. for (var index = 0; index < count; index++) {
  50349. var sprite = this.sprites[index];
  50350. if (!sprite) {
  50351. continue;
  50352. }
  50353. if (predicate) {
  50354. if (!predicate(sprite)) {
  50355. continue;
  50356. }
  50357. }
  50358. else if (!sprite.isPickable) {
  50359. continue;
  50360. }
  50361. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50362. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50363. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50364. if (ray.intersectsBoxMinMax(min, max)) {
  50365. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50366. if (distance > currentDistance) {
  50367. distance = currentDistance;
  50368. currentSprite = sprite;
  50369. if (fastCheck) {
  50370. break;
  50371. }
  50372. }
  50373. }
  50374. }
  50375. if (currentSprite) {
  50376. var result = new BABYLON.PickingInfo();
  50377. result.hit = true;
  50378. result.pickedSprite = currentSprite;
  50379. result.distance = distance;
  50380. return result;
  50381. }
  50382. return null;
  50383. };
  50384. SpriteManager.prototype.render = function () {
  50385. // Check
  50386. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50387. return;
  50388. var engine = this._scene.getEngine();
  50389. var baseSize = this._spriteTexture.getBaseSize();
  50390. // Sprites
  50391. var deltaTime = engine.getDeltaTime();
  50392. var max = Math.min(this._capacity, this.sprites.length);
  50393. var rowSize = baseSize.width / this.cellWidth;
  50394. var offset = 0;
  50395. for (var index = 0; index < max; index++) {
  50396. var sprite = this.sprites[index];
  50397. if (!sprite) {
  50398. continue;
  50399. }
  50400. sprite._animate(deltaTime);
  50401. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50402. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50403. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50404. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50405. }
  50406. this._buffer.update(this._vertexData);
  50407. // Render
  50408. var effect = this._effectBase;
  50409. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50410. effect = this._effectFog;
  50411. }
  50412. engine.enableEffect(effect);
  50413. var viewMatrix = this._scene.getViewMatrix();
  50414. effect.setTexture("diffuseSampler", this._spriteTexture);
  50415. effect.setMatrix("view", viewMatrix);
  50416. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50417. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50418. // Fog
  50419. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50420. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50421. effect.setColor3("vFogColor", this._scene.fogColor);
  50422. }
  50423. // VBOs
  50424. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50425. // Draw order
  50426. engine.setDepthFunctionToLessOrEqual();
  50427. effect.setBool("alphaTest", true);
  50428. engine.setColorWrite(false);
  50429. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50430. engine.setColorWrite(true);
  50431. effect.setBool("alphaTest", false);
  50432. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50433. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50434. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50435. };
  50436. SpriteManager.prototype.dispose = function () {
  50437. if (this._buffer) {
  50438. this._buffer.dispose();
  50439. this._buffer = null;
  50440. }
  50441. if (this._indexBuffer) {
  50442. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50443. this._indexBuffer = null;
  50444. }
  50445. if (this._spriteTexture) {
  50446. this._spriteTexture.dispose();
  50447. this._spriteTexture = null;
  50448. }
  50449. // Remove from scene
  50450. var index = this._scene.spriteManagers.indexOf(this);
  50451. this._scene.spriteManagers.splice(index, 1);
  50452. // Callback
  50453. this.onDisposeObservable.notifyObservers(this);
  50454. this.onDisposeObservable.clear();
  50455. };
  50456. return SpriteManager;
  50457. }());
  50458. BABYLON.SpriteManager = SpriteManager;
  50459. })(BABYLON || (BABYLON = {}));
  50460. //# sourceMappingURL=babylon.spriteManager.js.map
  50461. "use strict";
  50462. var BABYLON;
  50463. (function (BABYLON) {
  50464. var Sprite = /** @class */ (function () {
  50465. function Sprite(name, manager) {
  50466. this.name = name;
  50467. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50468. this.width = 1.0;
  50469. this.height = 1.0;
  50470. this.angle = 0;
  50471. this.cellIndex = 0;
  50472. this.invertU = 0;
  50473. this.invertV = 0;
  50474. this.animations = new Array();
  50475. this.isPickable = false;
  50476. this._animationStarted = false;
  50477. this._loopAnimation = false;
  50478. this._fromIndex = 0;
  50479. this._toIndex = 0;
  50480. this._delay = 0;
  50481. this._direction = 1;
  50482. this._time = 0;
  50483. this._manager = manager;
  50484. this._manager.sprites.push(this);
  50485. this.position = BABYLON.Vector3.Zero();
  50486. }
  50487. Object.defineProperty(Sprite.prototype, "size", {
  50488. get: function () {
  50489. return this.width;
  50490. },
  50491. set: function (value) {
  50492. this.width = value;
  50493. this.height = value;
  50494. },
  50495. enumerable: true,
  50496. configurable: true
  50497. });
  50498. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50499. this._fromIndex = from;
  50500. this._toIndex = to;
  50501. this._loopAnimation = loop;
  50502. this._delay = delay;
  50503. this._animationStarted = true;
  50504. this._direction = from < to ? 1 : -1;
  50505. this.cellIndex = from;
  50506. this._time = 0;
  50507. this._onAnimationEnd = onAnimationEnd;
  50508. };
  50509. Sprite.prototype.stopAnimation = function () {
  50510. this._animationStarted = false;
  50511. };
  50512. Sprite.prototype._animate = function (deltaTime) {
  50513. if (!this._animationStarted)
  50514. return;
  50515. this._time += deltaTime;
  50516. if (this._time > this._delay) {
  50517. this._time = this._time % this._delay;
  50518. this.cellIndex += this._direction;
  50519. if (this.cellIndex > this._toIndex) {
  50520. if (this._loopAnimation) {
  50521. this.cellIndex = this._fromIndex;
  50522. }
  50523. else {
  50524. this.cellIndex = this._toIndex;
  50525. this._animationStarted = false;
  50526. if (this._onAnimationEnd) {
  50527. this._onAnimationEnd();
  50528. }
  50529. if (this.disposeWhenFinishedAnimating) {
  50530. this.dispose();
  50531. }
  50532. }
  50533. }
  50534. }
  50535. };
  50536. Sprite.prototype.dispose = function () {
  50537. for (var i = 0; i < this._manager.sprites.length; i++) {
  50538. if (this._manager.sprites[i] == this) {
  50539. this._manager.sprites.splice(i, 1);
  50540. }
  50541. }
  50542. };
  50543. return Sprite;
  50544. }());
  50545. BABYLON.Sprite = Sprite;
  50546. })(BABYLON || (BABYLON = {}));
  50547. //# sourceMappingURL=babylon.sprite.js.map
  50548. "use strict";
  50549. var BABYLON;
  50550. (function (BABYLON) {
  50551. var IntersectionInfo = /** @class */ (function () {
  50552. function IntersectionInfo(bu, bv, distance) {
  50553. this.bu = bu;
  50554. this.bv = bv;
  50555. this.distance = distance;
  50556. this.faceId = 0;
  50557. this.subMeshId = 0;
  50558. }
  50559. return IntersectionInfo;
  50560. }());
  50561. BABYLON.IntersectionInfo = IntersectionInfo;
  50562. var PickingInfo = /** @class */ (function () {
  50563. function PickingInfo() {
  50564. this.hit = false;
  50565. this.distance = 0;
  50566. this.pickedPoint = null;
  50567. this.pickedMesh = null;
  50568. this.bu = 0;
  50569. this.bv = 0;
  50570. this.faceId = -1;
  50571. this.subMeshId = 0;
  50572. this.pickedSprite = null;
  50573. }
  50574. // Methods
  50575. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50576. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50577. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50578. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50579. return null;
  50580. }
  50581. var indices = this.pickedMesh.getIndices();
  50582. if (!indices) {
  50583. return null;
  50584. }
  50585. var result;
  50586. if (useVerticesNormals) {
  50587. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50588. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50589. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50590. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50591. normal0 = normal0.scale(this.bu);
  50592. normal1 = normal1.scale(this.bv);
  50593. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50594. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50595. }
  50596. else {
  50597. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50598. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50599. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50600. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50601. var p1p2 = vertex1.subtract(vertex2);
  50602. var p3p2 = vertex3.subtract(vertex2);
  50603. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50604. }
  50605. if (useWorldCoordinates) {
  50606. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50607. }
  50608. return BABYLON.Vector3.Normalize(result);
  50609. };
  50610. PickingInfo.prototype.getTextureCoordinates = function () {
  50611. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50612. return null;
  50613. }
  50614. var indices = this.pickedMesh.getIndices();
  50615. if (!indices) {
  50616. return null;
  50617. }
  50618. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50619. if (!uvs) {
  50620. return null;
  50621. }
  50622. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50623. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50624. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50625. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50626. uv1 = uv1.scale(this.bu);
  50627. uv2 = uv2.scale(this.bv);
  50628. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50629. };
  50630. return PickingInfo;
  50631. }());
  50632. BABYLON.PickingInfo = PickingInfo;
  50633. })(BABYLON || (BABYLON = {}));
  50634. //# sourceMappingURL=babylon.pickingInfo.js.map
  50635. "use strict";
  50636. var BABYLON;
  50637. (function (BABYLON) {
  50638. var Ray = /** @class */ (function () {
  50639. function Ray(origin, direction, length) {
  50640. if (length === void 0) { length = Number.MAX_VALUE; }
  50641. this.origin = origin;
  50642. this.direction = direction;
  50643. this.length = length;
  50644. }
  50645. // Methods
  50646. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50647. var d = 0.0;
  50648. var maxValue = Number.MAX_VALUE;
  50649. var inv;
  50650. var min;
  50651. var max;
  50652. var temp;
  50653. if (Math.abs(this.direction.x) < 0.0000001) {
  50654. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50655. return false;
  50656. }
  50657. }
  50658. else {
  50659. inv = 1.0 / this.direction.x;
  50660. min = (minimum.x - this.origin.x) * inv;
  50661. max = (maximum.x - this.origin.x) * inv;
  50662. if (max === -Infinity) {
  50663. max = Infinity;
  50664. }
  50665. if (min > max) {
  50666. temp = min;
  50667. min = max;
  50668. max = temp;
  50669. }
  50670. d = Math.max(min, d);
  50671. maxValue = Math.min(max, maxValue);
  50672. if (d > maxValue) {
  50673. return false;
  50674. }
  50675. }
  50676. if (Math.abs(this.direction.y) < 0.0000001) {
  50677. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50678. return false;
  50679. }
  50680. }
  50681. else {
  50682. inv = 1.0 / this.direction.y;
  50683. min = (minimum.y - this.origin.y) * inv;
  50684. max = (maximum.y - this.origin.y) * inv;
  50685. if (max === -Infinity) {
  50686. max = Infinity;
  50687. }
  50688. if (min > max) {
  50689. temp = min;
  50690. min = max;
  50691. max = temp;
  50692. }
  50693. d = Math.max(min, d);
  50694. maxValue = Math.min(max, maxValue);
  50695. if (d > maxValue) {
  50696. return false;
  50697. }
  50698. }
  50699. if (Math.abs(this.direction.z) < 0.0000001) {
  50700. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50701. return false;
  50702. }
  50703. }
  50704. else {
  50705. inv = 1.0 / this.direction.z;
  50706. min = (minimum.z - this.origin.z) * inv;
  50707. max = (maximum.z - this.origin.z) * inv;
  50708. if (max === -Infinity) {
  50709. max = Infinity;
  50710. }
  50711. if (min > max) {
  50712. temp = min;
  50713. min = max;
  50714. max = temp;
  50715. }
  50716. d = Math.max(min, d);
  50717. maxValue = Math.min(max, maxValue);
  50718. if (d > maxValue) {
  50719. return false;
  50720. }
  50721. }
  50722. return true;
  50723. };
  50724. Ray.prototype.intersectsBox = function (box) {
  50725. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50726. };
  50727. Ray.prototype.intersectsSphere = function (sphere) {
  50728. var x = sphere.center.x - this.origin.x;
  50729. var y = sphere.center.y - this.origin.y;
  50730. var z = sphere.center.z - this.origin.z;
  50731. var pyth = (x * x) + (y * y) + (z * z);
  50732. var rr = sphere.radius * sphere.radius;
  50733. if (pyth <= rr) {
  50734. return true;
  50735. }
  50736. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50737. if (dot < 0.0) {
  50738. return false;
  50739. }
  50740. var temp = pyth - (dot * dot);
  50741. return temp <= rr;
  50742. };
  50743. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50744. if (!this._edge1) {
  50745. this._edge1 = BABYLON.Vector3.Zero();
  50746. this._edge2 = BABYLON.Vector3.Zero();
  50747. this._pvec = BABYLON.Vector3.Zero();
  50748. this._tvec = BABYLON.Vector3.Zero();
  50749. this._qvec = BABYLON.Vector3.Zero();
  50750. }
  50751. vertex1.subtractToRef(vertex0, this._edge1);
  50752. vertex2.subtractToRef(vertex0, this._edge2);
  50753. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50754. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50755. if (det === 0) {
  50756. return null;
  50757. }
  50758. var invdet = 1 / det;
  50759. this.origin.subtractToRef(vertex0, this._tvec);
  50760. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50761. if (bu < 0 || bu > 1.0) {
  50762. return null;
  50763. }
  50764. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50765. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50766. if (bv < 0 || bu + bv > 1.0) {
  50767. return null;
  50768. }
  50769. //check if the distance is longer than the predefined length.
  50770. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50771. if (distance > this.length) {
  50772. return null;
  50773. }
  50774. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50775. };
  50776. Ray.prototype.intersectsPlane = function (plane) {
  50777. var distance;
  50778. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50779. if (Math.abs(result1) < 9.99999997475243E-07) {
  50780. return null;
  50781. }
  50782. else {
  50783. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50784. distance = (-plane.d - result2) / result1;
  50785. if (distance < 0.0) {
  50786. if (distance < -9.99999997475243E-07) {
  50787. return null;
  50788. }
  50789. else {
  50790. return 0;
  50791. }
  50792. }
  50793. return distance;
  50794. }
  50795. };
  50796. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50797. var tm = BABYLON.Tmp.Matrix[0];
  50798. mesh.getWorldMatrix().invertToRef(tm);
  50799. if (this._tmpRay) {
  50800. Ray.TransformToRef(this, tm, this._tmpRay);
  50801. }
  50802. else {
  50803. this._tmpRay = Ray.Transform(this, tm);
  50804. }
  50805. return mesh.intersects(this._tmpRay, fastCheck);
  50806. };
  50807. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50808. if (results) {
  50809. results.length = 0;
  50810. }
  50811. else {
  50812. results = [];
  50813. }
  50814. for (var i = 0; i < meshes.length; i++) {
  50815. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50816. if (pickInfo.hit) {
  50817. results.push(pickInfo);
  50818. }
  50819. }
  50820. results.sort(this._comparePickingInfo);
  50821. return results;
  50822. };
  50823. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50824. if (pickingInfoA.distance < pickingInfoB.distance) {
  50825. return -1;
  50826. }
  50827. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50828. return 1;
  50829. }
  50830. else {
  50831. return 0;
  50832. }
  50833. };
  50834. /**
  50835. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50836. * @param sega the first point of the segment to test the intersection against
  50837. * @param segb the second point of the segment to test the intersection against
  50838. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50839. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50840. */
  50841. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50842. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50843. var u = segb.subtract(sega);
  50844. var v = rsegb.subtract(this.origin);
  50845. var w = sega.subtract(this.origin);
  50846. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50847. var b = BABYLON.Vector3.Dot(u, v);
  50848. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50849. var d = BABYLON.Vector3.Dot(u, w);
  50850. var e = BABYLON.Vector3.Dot(v, w);
  50851. var D = a * c - b * b; // always >= 0
  50852. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50853. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50854. // compute the line parameters of the two closest points
  50855. if (D < Ray.smallnum) {
  50856. sN = 0.0; // force using point P0 on segment S1
  50857. sD = 1.0; // to prevent possible division by 0.0 later
  50858. tN = e;
  50859. tD = c;
  50860. }
  50861. else {
  50862. sN = (b * e - c * d);
  50863. tN = (a * e - b * d);
  50864. if (sN < 0.0) {
  50865. sN = 0.0;
  50866. tN = e;
  50867. tD = c;
  50868. }
  50869. else if (sN > sD) {
  50870. sN = sD;
  50871. tN = e + b;
  50872. tD = c;
  50873. }
  50874. }
  50875. if (tN < 0.0) {
  50876. tN = 0.0;
  50877. // recompute sc for this edge
  50878. if (-d < 0.0) {
  50879. sN = 0.0;
  50880. }
  50881. else if (-d > a)
  50882. sN = sD;
  50883. else {
  50884. sN = -d;
  50885. sD = a;
  50886. }
  50887. }
  50888. else if (tN > tD) {
  50889. tN = tD;
  50890. // recompute sc for this edge
  50891. if ((-d + b) < 0.0) {
  50892. sN = 0;
  50893. }
  50894. else if ((-d + b) > a) {
  50895. sN = sD;
  50896. }
  50897. else {
  50898. sN = (-d + b);
  50899. sD = a;
  50900. }
  50901. }
  50902. // finally do the division to get sc and tc
  50903. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50904. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50905. // get the difference of the two closest points
  50906. var qtc = v.multiplyByFloats(tc, tc, tc);
  50907. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50908. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50909. if (isIntersected) {
  50910. return qtc.length();
  50911. }
  50912. return -1;
  50913. };
  50914. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50915. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50916. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50917. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50918. this.direction.normalize();
  50919. return this;
  50920. };
  50921. // Statics
  50922. Ray.Zero = function () {
  50923. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50924. };
  50925. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50926. var result = Ray.Zero();
  50927. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50928. };
  50929. /**
  50930. * 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
  50931. * transformed to the given world matrix.
  50932. * @param origin The origin point
  50933. * @param end The end point
  50934. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50935. */
  50936. Ray.CreateNewFromTo = function (origin, end, world) {
  50937. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50938. var direction = end.subtract(origin);
  50939. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50940. direction.normalize();
  50941. return Ray.Transform(new Ray(origin, direction, length), world);
  50942. };
  50943. Ray.Transform = function (ray, matrix) {
  50944. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50945. Ray.TransformToRef(ray, matrix, result);
  50946. return result;
  50947. };
  50948. Ray.TransformToRef = function (ray, matrix, result) {
  50949. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50950. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50951. result.length = ray.length;
  50952. var dir = result.direction;
  50953. var len = dir.length();
  50954. if (!(len === 0 || len === 1)) {
  50955. var num = 1.0 / len;
  50956. dir.x *= num;
  50957. dir.y *= num;
  50958. dir.z *= num;
  50959. result.length *= len;
  50960. }
  50961. };
  50962. Ray.smallnum = 0.00000001;
  50963. Ray.rayl = 10e8;
  50964. return Ray;
  50965. }());
  50966. BABYLON.Ray = Ray;
  50967. })(BABYLON || (BABYLON = {}));
  50968. //# sourceMappingURL=babylon.ray.js.map
  50969. "use strict";
  50970. var BABYLON;
  50971. (function (BABYLON) {
  50972. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50973. if (boxMin.x > sphereCenter.x + sphereRadius)
  50974. return false;
  50975. if (sphereCenter.x - sphereRadius > boxMax.x)
  50976. return false;
  50977. if (boxMin.y > sphereCenter.y + sphereRadius)
  50978. return false;
  50979. if (sphereCenter.y - sphereRadius > boxMax.y)
  50980. return false;
  50981. if (boxMin.z > sphereCenter.z + sphereRadius)
  50982. return false;
  50983. if (sphereCenter.z - sphereRadius > boxMax.z)
  50984. return false;
  50985. return true;
  50986. };
  50987. var getLowestRoot = (function () {
  50988. var result = { root: 0, found: false };
  50989. return function (a, b, c, maxR) {
  50990. result.root = 0;
  50991. result.found = false;
  50992. var determinant = b * b - 4.0 * a * c;
  50993. if (determinant < 0)
  50994. return result;
  50995. var sqrtD = Math.sqrt(determinant);
  50996. var r1 = (-b - sqrtD) / (2.0 * a);
  50997. var r2 = (-b + sqrtD) / (2.0 * a);
  50998. if (r1 > r2) {
  50999. var temp = r2;
  51000. r2 = r1;
  51001. r1 = temp;
  51002. }
  51003. if (r1 > 0 && r1 < maxR) {
  51004. result.root = r1;
  51005. result.found = true;
  51006. return result;
  51007. }
  51008. if (r2 > 0 && r2 < maxR) {
  51009. result.root = r2;
  51010. result.found = true;
  51011. return result;
  51012. }
  51013. return result;
  51014. };
  51015. })();
  51016. var Collider = /** @class */ (function () {
  51017. function Collider() {
  51018. this._collisionPoint = BABYLON.Vector3.Zero();
  51019. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  51020. this._tempVector = BABYLON.Vector3.Zero();
  51021. this._tempVector2 = BABYLON.Vector3.Zero();
  51022. this._tempVector3 = BABYLON.Vector3.Zero();
  51023. this._tempVector4 = BABYLON.Vector3.Zero();
  51024. this._edge = BABYLON.Vector3.Zero();
  51025. this._baseToVertex = BABYLON.Vector3.Zero();
  51026. this._destinationPoint = BABYLON.Vector3.Zero();
  51027. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  51028. this._displacementVector = BABYLON.Vector3.Zero();
  51029. this._radius = BABYLON.Vector3.One();
  51030. this._retry = 0;
  51031. this._basePointWorld = BABYLON.Vector3.Zero();
  51032. this._velocityWorld = BABYLON.Vector3.Zero();
  51033. this._normalizedVelocity = BABYLON.Vector3.Zero();
  51034. this._collisionMask = -1;
  51035. }
  51036. Object.defineProperty(Collider.prototype, "collisionMask", {
  51037. get: function () {
  51038. return this._collisionMask;
  51039. },
  51040. set: function (mask) {
  51041. this._collisionMask = !isNaN(mask) ? mask : -1;
  51042. },
  51043. enumerable: true,
  51044. configurable: true
  51045. });
  51046. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  51047. /**
  51048. * Gets the plane normal used to compute the sliding response (in local space)
  51049. */
  51050. get: function () {
  51051. return this._slidePlaneNormal;
  51052. },
  51053. enumerable: true,
  51054. configurable: true
  51055. });
  51056. // Methods
  51057. Collider.prototype._initialize = function (source, dir, e) {
  51058. this._velocity = dir;
  51059. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  51060. this._basePoint = source;
  51061. source.multiplyToRef(this._radius, this._basePointWorld);
  51062. dir.multiplyToRef(this._radius, this._velocityWorld);
  51063. this._velocityWorldLength = this._velocityWorld.length();
  51064. this._epsilon = e;
  51065. this.collisionFound = false;
  51066. };
  51067. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  51068. pa.subtractToRef(point, this._tempVector);
  51069. pb.subtractToRef(point, this._tempVector2);
  51070. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  51071. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51072. if (d < 0)
  51073. return false;
  51074. pc.subtractToRef(point, this._tempVector3);
  51075. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  51076. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51077. if (d < 0)
  51078. return false;
  51079. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  51080. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51081. return d >= 0;
  51082. };
  51083. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  51084. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  51085. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  51086. if (distance > this._velocityWorldLength + max + sphereRadius) {
  51087. return false;
  51088. }
  51089. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  51090. return false;
  51091. return true;
  51092. };
  51093. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  51094. var t0;
  51095. var embeddedInPlane = false;
  51096. //defensive programming, actually not needed.
  51097. if (!trianglePlaneArray) {
  51098. trianglePlaneArray = [];
  51099. }
  51100. if (!trianglePlaneArray[faceIndex]) {
  51101. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  51102. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  51103. }
  51104. var trianglePlane = trianglePlaneArray[faceIndex];
  51105. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  51106. return;
  51107. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  51108. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  51109. if (normalDotVelocity == 0) {
  51110. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  51111. return;
  51112. embeddedInPlane = true;
  51113. t0 = 0;
  51114. }
  51115. else {
  51116. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51117. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51118. if (t0 > t1) {
  51119. var temp = t1;
  51120. t1 = t0;
  51121. t0 = temp;
  51122. }
  51123. if (t0 > 1.0 || t1 < 0.0)
  51124. return;
  51125. if (t0 < 0)
  51126. t0 = 0;
  51127. if (t0 > 1.0)
  51128. t0 = 1.0;
  51129. }
  51130. this._collisionPoint.copyFromFloats(0, 0, 0);
  51131. var found = false;
  51132. var t = 1.0;
  51133. if (!embeddedInPlane) {
  51134. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  51135. this._velocity.scaleToRef(t0, this._tempVector);
  51136. this._planeIntersectionPoint.addInPlace(this._tempVector);
  51137. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  51138. found = true;
  51139. t = t0;
  51140. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  51141. }
  51142. }
  51143. if (!found) {
  51144. var velocitySquaredLength = this._velocity.lengthSquared();
  51145. var a = velocitySquaredLength;
  51146. this._basePoint.subtractToRef(p1, this._tempVector);
  51147. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51148. var c = this._tempVector.lengthSquared() - 1.0;
  51149. var lowestRoot = getLowestRoot(a, b, c, t);
  51150. if (lowestRoot.found) {
  51151. t = lowestRoot.root;
  51152. found = true;
  51153. this._collisionPoint.copyFrom(p1);
  51154. }
  51155. this._basePoint.subtractToRef(p2, this._tempVector);
  51156. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51157. c = this._tempVector.lengthSquared() - 1.0;
  51158. lowestRoot = getLowestRoot(a, b, c, t);
  51159. if (lowestRoot.found) {
  51160. t = lowestRoot.root;
  51161. found = true;
  51162. this._collisionPoint.copyFrom(p2);
  51163. }
  51164. this._basePoint.subtractToRef(p3, this._tempVector);
  51165. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51166. c = this._tempVector.lengthSquared() - 1.0;
  51167. lowestRoot = getLowestRoot(a, b, c, t);
  51168. if (lowestRoot.found) {
  51169. t = lowestRoot.root;
  51170. found = true;
  51171. this._collisionPoint.copyFrom(p3);
  51172. }
  51173. p2.subtractToRef(p1, this._edge);
  51174. p1.subtractToRef(this._basePoint, this._baseToVertex);
  51175. var edgeSquaredLength = this._edge.lengthSquared();
  51176. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51177. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51178. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51179. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51180. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51181. lowestRoot = getLowestRoot(a, b, c, t);
  51182. if (lowestRoot.found) {
  51183. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51184. if (f >= 0.0 && f <= 1.0) {
  51185. t = lowestRoot.root;
  51186. found = true;
  51187. this._edge.scaleInPlace(f);
  51188. p1.addToRef(this._edge, this._collisionPoint);
  51189. }
  51190. }
  51191. p3.subtractToRef(p2, this._edge);
  51192. p2.subtractToRef(this._basePoint, this._baseToVertex);
  51193. edgeSquaredLength = this._edge.lengthSquared();
  51194. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51195. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51196. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51197. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51198. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51199. lowestRoot = getLowestRoot(a, b, c, t);
  51200. if (lowestRoot.found) {
  51201. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51202. if (f >= 0.0 && f <= 1.0) {
  51203. t = lowestRoot.root;
  51204. found = true;
  51205. this._edge.scaleInPlace(f);
  51206. p2.addToRef(this._edge, this._collisionPoint);
  51207. }
  51208. }
  51209. p1.subtractToRef(p3, this._edge);
  51210. p3.subtractToRef(this._basePoint, this._baseToVertex);
  51211. edgeSquaredLength = this._edge.lengthSquared();
  51212. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51213. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51214. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51215. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51216. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51217. lowestRoot = getLowestRoot(a, b, c, t);
  51218. if (lowestRoot.found) {
  51219. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51220. if (f >= 0.0 && f <= 1.0) {
  51221. t = lowestRoot.root;
  51222. found = true;
  51223. this._edge.scaleInPlace(f);
  51224. p3.addToRef(this._edge, this._collisionPoint);
  51225. }
  51226. }
  51227. }
  51228. if (found) {
  51229. var distToCollision = t * this._velocity.length();
  51230. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51231. if (!this.intersectionPoint) {
  51232. this.intersectionPoint = this._collisionPoint.clone();
  51233. }
  51234. else {
  51235. this.intersectionPoint.copyFrom(this._collisionPoint);
  51236. }
  51237. this._nearestDistance = distToCollision;
  51238. this.collisionFound = true;
  51239. }
  51240. }
  51241. };
  51242. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51243. for (var i = indexStart; i < indexEnd; i += 3) {
  51244. var p1 = pts[indices[i] - decal];
  51245. var p2 = pts[indices[i + 1] - decal];
  51246. var p3 = pts[indices[i + 2] - decal];
  51247. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51248. }
  51249. };
  51250. Collider.prototype._getResponse = function (pos, vel) {
  51251. pos.addToRef(vel, this._destinationPoint);
  51252. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51253. this._basePoint.addToRef(vel, pos);
  51254. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51255. this._slidePlaneNormal.normalize();
  51256. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51257. pos.addInPlace(this._displacementVector);
  51258. this.intersectionPoint.addInPlace(this._displacementVector);
  51259. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51260. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51261. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51262. };
  51263. return Collider;
  51264. }());
  51265. BABYLON.Collider = Collider;
  51266. })(BABYLON || (BABYLON = {}));
  51267. //# sourceMappingURL=babylon.collider.js.map
  51268. "use strict";
  51269. var BABYLON;
  51270. (function (BABYLON) {
  51271. //WebWorker code will be inserted to this variable.
  51272. BABYLON.CollisionWorker = "";
  51273. var WorkerTaskType;
  51274. (function (WorkerTaskType) {
  51275. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51276. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51277. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51278. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51279. var WorkerReplyType;
  51280. (function (WorkerReplyType) {
  51281. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51282. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51283. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51284. var CollisionCoordinatorWorker = /** @class */ (function () {
  51285. function CollisionCoordinatorWorker() {
  51286. var _this = this;
  51287. this._scaledPosition = BABYLON.Vector3.Zero();
  51288. this._scaledVelocity = BABYLON.Vector3.Zero();
  51289. this.onMeshUpdated = function (transformNode) {
  51290. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51291. };
  51292. this.onGeometryUpdated = function (geometry) {
  51293. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51294. };
  51295. this._afterRender = function () {
  51296. if (!_this._init)
  51297. return;
  51298. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51299. return;
  51300. }
  51301. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51302. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51303. if (_this._runningUpdated > 4) {
  51304. return;
  51305. }
  51306. ++_this._runningUpdated;
  51307. var payload = {
  51308. updatedMeshes: _this._addUpdateMeshesList,
  51309. updatedGeometries: _this._addUpdateGeometriesList,
  51310. removedGeometries: _this._toRemoveGeometryArray,
  51311. removedMeshes: _this._toRemoveMeshesArray
  51312. };
  51313. var message = {
  51314. payload: payload,
  51315. taskType: WorkerTaskType.UPDATE
  51316. };
  51317. var serializable = [];
  51318. for (var id in payload.updatedGeometries) {
  51319. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51320. //prepare transferables
  51321. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51322. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51323. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51324. }
  51325. }
  51326. _this._worker.postMessage(message, serializable);
  51327. _this._addUpdateMeshesList = {};
  51328. _this._addUpdateGeometriesList = {};
  51329. _this._toRemoveGeometryArray = [];
  51330. _this._toRemoveMeshesArray = [];
  51331. };
  51332. this._onMessageFromWorker = function (e) {
  51333. var returnData = e.data;
  51334. if (returnData.error != WorkerReplyType.SUCCESS) {
  51335. //TODO what errors can be returned from the worker?
  51336. BABYLON.Tools.Warn("error returned from worker!");
  51337. return;
  51338. }
  51339. switch (returnData.taskType) {
  51340. case WorkerTaskType.INIT:
  51341. _this._init = true;
  51342. //Update the worked with ALL of the scene's current state
  51343. _this._scene.meshes.forEach(function (mesh) {
  51344. _this.onMeshAdded(mesh);
  51345. });
  51346. _this._scene.getGeometries().forEach(function (geometry) {
  51347. _this.onGeometryAdded(geometry);
  51348. });
  51349. break;
  51350. case WorkerTaskType.UPDATE:
  51351. _this._runningUpdated--;
  51352. break;
  51353. case WorkerTaskType.COLLIDE:
  51354. var returnPayload = returnData.payload;
  51355. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51356. return;
  51357. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51358. if (callback) {
  51359. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51360. if (mesh) {
  51361. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51362. }
  51363. }
  51364. //cleanup
  51365. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51366. break;
  51367. }
  51368. };
  51369. this._collisionsCallbackArray = [];
  51370. this._init = false;
  51371. this._runningUpdated = 0;
  51372. this._addUpdateMeshesList = {};
  51373. this._addUpdateGeometriesList = {};
  51374. this._toRemoveGeometryArray = [];
  51375. this._toRemoveMeshesArray = [];
  51376. }
  51377. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51378. if (!this._init)
  51379. return;
  51380. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51381. return;
  51382. position.divideToRef(collider._radius, this._scaledPosition);
  51383. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51384. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51385. var payload = {
  51386. collider: {
  51387. position: this._scaledPosition.asArray(),
  51388. velocity: this._scaledVelocity.asArray(),
  51389. radius: collider._radius.asArray()
  51390. },
  51391. collisionId: collisionIndex,
  51392. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51393. maximumRetry: maximumRetry
  51394. };
  51395. var message = {
  51396. payload: payload,
  51397. taskType: WorkerTaskType.COLLIDE
  51398. };
  51399. this._worker.postMessage(message);
  51400. };
  51401. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51402. this._scene = scene;
  51403. this._scene.registerAfterRender(this._afterRender);
  51404. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51405. this._worker = new Worker(workerUrl);
  51406. this._worker.onmessage = this._onMessageFromWorker;
  51407. var message = {
  51408. payload: {},
  51409. taskType: WorkerTaskType.INIT
  51410. };
  51411. this._worker.postMessage(message);
  51412. };
  51413. CollisionCoordinatorWorker.prototype.destroy = function () {
  51414. this._scene.unregisterAfterRender(this._afterRender);
  51415. this._worker.terminate();
  51416. };
  51417. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51418. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51419. this.onMeshUpdated(mesh);
  51420. };
  51421. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51422. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51423. };
  51424. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51425. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51426. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51427. this.onGeometryUpdated(geometry);
  51428. };
  51429. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51430. this._toRemoveGeometryArray.push(geometry.id);
  51431. };
  51432. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51433. var submeshes = [];
  51434. if (mesh.subMeshes) {
  51435. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51436. var boundingInfo = sm.getBoundingInfo();
  51437. return {
  51438. position: idx,
  51439. verticesStart: sm.verticesStart,
  51440. verticesCount: sm.verticesCount,
  51441. indexStart: sm.indexStart,
  51442. indexCount: sm.indexCount,
  51443. hasMaterial: !!sm.getMaterial(),
  51444. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51445. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51446. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51447. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51448. };
  51449. });
  51450. }
  51451. var geometryId = null;
  51452. if (mesh instanceof BABYLON.Mesh) {
  51453. var geometry = mesh.geometry;
  51454. geometryId = geometry ? geometry.id : null;
  51455. }
  51456. else if (mesh instanceof BABYLON.InstancedMesh) {
  51457. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51458. geometryId = geometry ? geometry.id : null;
  51459. }
  51460. var boundingInfo = mesh.getBoundingInfo();
  51461. return {
  51462. uniqueId: mesh.uniqueId,
  51463. id: mesh.id,
  51464. name: mesh.name,
  51465. geometryId: geometryId,
  51466. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51467. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51468. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51469. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51470. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51471. subMeshes: submeshes,
  51472. checkCollisions: mesh.checkCollisions
  51473. };
  51474. };
  51475. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51476. return {
  51477. id: geometry.id,
  51478. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51479. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51480. indices: new Uint32Array(geometry.getIndices() || []),
  51481. };
  51482. };
  51483. return CollisionCoordinatorWorker;
  51484. }());
  51485. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51486. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51487. function CollisionCoordinatorLegacy() {
  51488. this._scaledPosition = BABYLON.Vector3.Zero();
  51489. this._scaledVelocity = BABYLON.Vector3.Zero();
  51490. this._finalPosition = BABYLON.Vector3.Zero();
  51491. }
  51492. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51493. position.divideToRef(collider._radius, this._scaledPosition);
  51494. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51495. collider.collidedMesh = null;
  51496. collider._retry = 0;
  51497. collider._initialVelocity = this._scaledVelocity;
  51498. collider._initialPosition = this._scaledPosition;
  51499. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51500. this._finalPosition.multiplyInPlace(collider._radius);
  51501. //run the callback
  51502. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51503. };
  51504. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51505. this._scene = scene;
  51506. };
  51507. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51508. //Legacy need no destruction method.
  51509. };
  51510. //No update in legacy mode
  51511. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51512. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51513. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51514. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51515. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51516. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51517. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51518. if (excludedMesh === void 0) { excludedMesh = null; }
  51519. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51520. if (collider._retry >= maximumRetry) {
  51521. finalPosition.copyFrom(position);
  51522. return;
  51523. }
  51524. // Check if this is a mesh else camera or -1
  51525. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51526. collider._initialize(position, velocity, closeDistance);
  51527. // Check all meshes
  51528. for (var index = 0; index < this._scene.meshes.length; index++) {
  51529. var mesh = this._scene.meshes[index];
  51530. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51531. mesh._checkCollision(collider);
  51532. }
  51533. }
  51534. if (!collider.collisionFound) {
  51535. position.addToRef(velocity, finalPosition);
  51536. return;
  51537. }
  51538. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51539. collider._getResponse(position, velocity);
  51540. }
  51541. if (velocity.length() <= closeDistance) {
  51542. finalPosition.copyFrom(position);
  51543. return;
  51544. }
  51545. collider._retry++;
  51546. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51547. };
  51548. return CollisionCoordinatorLegacy;
  51549. }());
  51550. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51551. })(BABYLON || (BABYLON = {}));
  51552. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51553. "use strict";
  51554. var BABYLON;
  51555. (function (BABYLON) {
  51556. /**
  51557. * A particle represents one of the element emitted by a particle system.
  51558. * This is mainly define by its coordinates, direction, velocity and age.
  51559. */
  51560. var Particle = /** @class */ (function () {
  51561. /**
  51562. * Creates a new instance of @see Particle
  51563. * @param particleSystem the particle system the particle belongs to
  51564. */
  51565. function Particle(
  51566. /**
  51567. * particleSystem the particle system the particle belongs to.
  51568. */
  51569. particleSystem) {
  51570. this.particleSystem = particleSystem;
  51571. /**
  51572. * The world position of the particle in the scene.
  51573. */
  51574. this.position = BABYLON.Vector3.Zero();
  51575. /**
  51576. * The world direction of the particle in the scene.
  51577. */
  51578. this.direction = BABYLON.Vector3.Zero();
  51579. /**
  51580. * The color of the particle.
  51581. */
  51582. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51583. /**
  51584. * The color change of the particle per step.
  51585. */
  51586. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51587. /**
  51588. * Defines how long will the life of the particle be.
  51589. */
  51590. this.lifeTime = 1.0;
  51591. /**
  51592. * The current age of the particle.
  51593. */
  51594. this.age = 0;
  51595. /**
  51596. * The current size of the particle.
  51597. */
  51598. this.size = 0;
  51599. /**
  51600. * The current angle of the particle.
  51601. */
  51602. this.angle = 0;
  51603. /**
  51604. * Defines how fast is the angle changing.
  51605. */
  51606. this.angularSpeed = 0;
  51607. /**
  51608. * Defines the cell index used by the particle to be rendered from a sprite.
  51609. */
  51610. this.cellIndex = 0;
  51611. this._currentFrameCounter = 0;
  51612. if (!this.particleSystem.isAnimationSheetEnabled) {
  51613. return;
  51614. }
  51615. this.updateCellInfoFromSystem();
  51616. }
  51617. Particle.prototype.updateCellInfoFromSystem = function () {
  51618. this.cellIndex = this.particleSystem.startSpriteCellID;
  51619. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51620. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51621. }
  51622. else {
  51623. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51624. }
  51625. };
  51626. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51627. // (ageOffset / scaledUpdateSpeed) / available cells
  51628. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51629. this._currentFrameCounter += scaledUpdateSpeed;
  51630. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51631. this._currentFrameCounter = 0;
  51632. this.cellIndex++;
  51633. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51634. this.cellIndex = this.particleSystem.endSpriteCellID;
  51635. }
  51636. }
  51637. };
  51638. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51639. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51640. this.cellIndex++;
  51641. this._currentFrameCounter = 0;
  51642. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51643. if (this.particleSystem.spriteCellLoop) {
  51644. this.cellIndex = this.particleSystem.startSpriteCellID;
  51645. }
  51646. else {
  51647. this.cellIndex = this.particleSystem.endSpriteCellID;
  51648. }
  51649. }
  51650. }
  51651. else {
  51652. this._currentFrameCounter++;
  51653. }
  51654. };
  51655. /**
  51656. * Copy the properties of particle to another one.
  51657. * @param other the particle to copy the information to.
  51658. */
  51659. Particle.prototype.copyTo = function (other) {
  51660. other.position.copyFrom(this.position);
  51661. other.direction.copyFrom(this.direction);
  51662. other.color.copyFrom(this.color);
  51663. other.colorStep.copyFrom(this.colorStep);
  51664. other.lifeTime = this.lifeTime;
  51665. other.age = this.age;
  51666. other.size = this.size;
  51667. other.angle = this.angle;
  51668. other.angularSpeed = this.angularSpeed;
  51669. other.particleSystem = this.particleSystem;
  51670. other.cellIndex = this.cellIndex;
  51671. };
  51672. return Particle;
  51673. }());
  51674. BABYLON.Particle = Particle;
  51675. })(BABYLON || (BABYLON = {}));
  51676. //# sourceMappingURL=babylon.particle.js.map
  51677. "use strict";
  51678. var BABYLON;
  51679. (function (BABYLON) {
  51680. /**
  51681. * This represents a particle system in Babylon.
  51682. * 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.
  51683. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51684. * @example https://doc.babylonjs.com/babylon101/particles
  51685. */
  51686. var ParticleSystem = /** @class */ (function () {
  51687. /**
  51688. * Instantiates a particle system.
  51689. * 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.
  51690. * @param name The name of the particle system
  51691. * @param capacity The max number of particles alive at the same time
  51692. * @param scene The scene the particle system belongs to
  51693. * @param customEffect a custom effect used to change the way particles are rendered by default
  51694. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51695. * @param epsilon Offset used to render the particles
  51696. */
  51697. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51698. if (customEffect === void 0) { customEffect = null; }
  51699. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51700. if (epsilon === void 0) { epsilon = 0.01; }
  51701. var _this = this;
  51702. /**
  51703. * List of animations used by the particle system.
  51704. */
  51705. this.animations = [];
  51706. /**
  51707. * The rendering group used by the Particle system to chose when to render.
  51708. */
  51709. this.renderingGroupId = 0;
  51710. /**
  51711. * The emitter represents the Mesh or position we are attaching the particle system to.
  51712. */
  51713. this.emitter = null;
  51714. /**
  51715. * The maximum number of particles to emit per frame
  51716. */
  51717. this.emitRate = 10;
  51718. /**
  51719. * If you want to launch only a few particles at once, that can be done, as well.
  51720. */
  51721. this.manualEmitCount = -1;
  51722. /**
  51723. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51724. */
  51725. this.updateSpeed = 0.01;
  51726. /**
  51727. * The amount of time the particle system is running (depends of the overall update speed).
  51728. */
  51729. this.targetStopDuration = 0;
  51730. /**
  51731. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51732. */
  51733. this.disposeOnStop = false;
  51734. /**
  51735. * Minimum power of emitting particles.
  51736. */
  51737. this.minEmitPower = 1;
  51738. /**
  51739. * Maximum power of emitting particles.
  51740. */
  51741. this.maxEmitPower = 1;
  51742. /**
  51743. * Minimum life time of emitting particles.
  51744. */
  51745. this.minLifeTime = 1;
  51746. /**
  51747. * Maximum life time of emitting particles.
  51748. */
  51749. this.maxLifeTime = 1;
  51750. /**
  51751. * Minimum Size of emitting particles.
  51752. */
  51753. this.minSize = 1;
  51754. /**
  51755. * Maximum Size of emitting particles.
  51756. */
  51757. this.maxSize = 1;
  51758. /**
  51759. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51760. */
  51761. this.minAngularSpeed = 0;
  51762. /**
  51763. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51764. */
  51765. this.maxAngularSpeed = 0;
  51766. /**
  51767. * The layer mask we are rendering the particles through.
  51768. */
  51769. this.layerMask = 0x0FFFFFFF;
  51770. /**
  51771. * This can help using your own shader to render the particle system.
  51772. * The according effect will be created
  51773. */
  51774. this.customShader = null;
  51775. /**
  51776. * By default particle system starts as soon as they are created. This prevents the
  51777. * automatic start to happen and let you decide when to start emitting particles.
  51778. */
  51779. this.preventAutoStart = false;
  51780. /**
  51781. * Callback triggered when the particle animation is ending.
  51782. */
  51783. this.onAnimationEnd = null;
  51784. /**
  51785. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51786. */
  51787. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51788. /**
  51789. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51790. * to override the particles.
  51791. */
  51792. this.forceDepthWrite = false;
  51793. /**
  51794. * You can use gravity if you want to give an orientation to your particles.
  51795. */
  51796. this.gravity = BABYLON.Vector3.Zero();
  51797. /**
  51798. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51799. */
  51800. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51801. /**
  51802. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51803. */
  51804. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51805. /**
  51806. * Color the particle will have at the end of its lifetime.
  51807. */
  51808. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51809. /**
  51810. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51811. */
  51812. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51813. /**
  51814. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51815. */
  51816. this.spriteCellLoop = true;
  51817. /**
  51818. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51819. */
  51820. this.spriteCellChangeSpeed = 0;
  51821. /**
  51822. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51823. */
  51824. this.startSpriteCellID = 0;
  51825. /**
  51826. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51827. */
  51828. this.endSpriteCellID = 0;
  51829. /**
  51830. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51831. */
  51832. this.spriteCellWidth = 0;
  51833. /**
  51834. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51835. */
  51836. this.spriteCellHeight = 0;
  51837. /**
  51838. * An event triggered when the system is disposed.
  51839. */
  51840. this.onDisposeObservable = new BABYLON.Observable();
  51841. this._particles = new Array();
  51842. this._stockParticles = new Array();
  51843. this._newPartsExcess = 0;
  51844. this._vertexBuffers = {};
  51845. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51846. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51847. this._scaledDirection = BABYLON.Vector3.Zero();
  51848. this._scaledGravity = BABYLON.Vector3.Zero();
  51849. this._currentRenderId = -1;
  51850. this._started = false;
  51851. this._stopped = false;
  51852. this._actualFrame = 0;
  51853. this._vertexBufferSize = 11;
  51854. // start of sub system methods
  51855. /**
  51856. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51857. * Its lifetime will start back at 0.
  51858. */
  51859. this.recycleParticle = function (particle) {
  51860. var lastParticle = _this._particles.pop();
  51861. if (lastParticle !== particle) {
  51862. lastParticle.copyTo(particle);
  51863. }
  51864. _this._stockParticles.push(lastParticle);
  51865. };
  51866. this._createParticle = function () {
  51867. var particle;
  51868. if (_this._stockParticles.length !== 0) {
  51869. particle = _this._stockParticles.pop();
  51870. particle.age = 0;
  51871. particle.cellIndex = _this.startSpriteCellID;
  51872. }
  51873. else {
  51874. particle = new BABYLON.Particle(_this);
  51875. }
  51876. return particle;
  51877. };
  51878. this._emitFromParticle = function (particle) {
  51879. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51880. return;
  51881. }
  51882. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51883. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51884. subSystem._rootParticleSystem = _this;
  51885. _this.activeSubSystems.push(subSystem);
  51886. subSystem.start();
  51887. };
  51888. this._appendParticleVertexes = null;
  51889. this.id = name;
  51890. this.name = name;
  51891. this._capacity = capacity;
  51892. this._epsilon = epsilon;
  51893. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51894. if (isAnimationSheetEnabled) {
  51895. this._vertexBufferSize = 12;
  51896. }
  51897. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51898. this._customEffect = customEffect;
  51899. scene.particleSystems.push(this);
  51900. this._createIndexBuffer();
  51901. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51902. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51903. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51904. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51905. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51906. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51907. if (this._isAnimationSheetEnabled) {
  51908. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51909. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51910. }
  51911. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51912. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51913. this._vertexBuffers["options"] = options;
  51914. // Default emitter type
  51915. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51916. this.updateFunction = function (particles) {
  51917. for (var index = 0; index < particles.length; index++) {
  51918. var particle = particles[index];
  51919. particle.age += _this._scaledUpdateSpeed;
  51920. if (particle.age >= particle.lifeTime) {
  51921. _this._emitFromParticle(particle);
  51922. _this.recycleParticle(particle);
  51923. index--;
  51924. continue;
  51925. }
  51926. else {
  51927. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51928. particle.color.addInPlace(_this._scaledColorStep);
  51929. if (particle.color.a < 0)
  51930. particle.color.a = 0;
  51931. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51932. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51933. particle.position.addInPlace(_this._scaledDirection);
  51934. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51935. particle.direction.addInPlace(_this._scaledGravity);
  51936. if (_this._isAnimationSheetEnabled) {
  51937. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51938. }
  51939. }
  51940. }
  51941. };
  51942. }
  51943. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51944. /**
  51945. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51946. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51947. */
  51948. get: function () {
  51949. if (this.particleEmitterType.direction1) {
  51950. return this.particleEmitterType.direction1;
  51951. }
  51952. return BABYLON.Vector3.Zero();
  51953. },
  51954. set: function (value) {
  51955. if (this.particleEmitterType.direction1) {
  51956. this.particleEmitterType.direction1 = value;
  51957. }
  51958. },
  51959. enumerable: true,
  51960. configurable: true
  51961. });
  51962. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51963. /**
  51964. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51965. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51966. */
  51967. get: function () {
  51968. if (this.particleEmitterType.direction2) {
  51969. return this.particleEmitterType.direction2;
  51970. }
  51971. return BABYLON.Vector3.Zero();
  51972. },
  51973. set: function (value) {
  51974. if (this.particleEmitterType.direction2) {
  51975. this.particleEmitterType.direction2 = value;
  51976. }
  51977. },
  51978. enumerable: true,
  51979. configurable: true
  51980. });
  51981. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51982. /**
  51983. * 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.
  51984. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51985. */
  51986. get: function () {
  51987. if (this.particleEmitterType.minEmitBox) {
  51988. return this.particleEmitterType.minEmitBox;
  51989. }
  51990. return BABYLON.Vector3.Zero();
  51991. },
  51992. set: function (value) {
  51993. if (this.particleEmitterType.minEmitBox) {
  51994. this.particleEmitterType.minEmitBox = value;
  51995. }
  51996. },
  51997. enumerable: true,
  51998. configurable: true
  51999. });
  52000. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  52001. /**
  52002. * 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.
  52003. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52004. */
  52005. get: function () {
  52006. if (this.particleEmitterType.maxEmitBox) {
  52007. return this.particleEmitterType.maxEmitBox;
  52008. }
  52009. return BABYLON.Vector3.Zero();
  52010. },
  52011. set: function (value) {
  52012. if (this.particleEmitterType.maxEmitBox) {
  52013. this.particleEmitterType.maxEmitBox = value;
  52014. }
  52015. },
  52016. enumerable: true,
  52017. configurable: true
  52018. });
  52019. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  52020. /**
  52021. * Sets a callback that will be triggered when the system is disposed.
  52022. */
  52023. set: function (callback) {
  52024. if (this._onDisposeObserver) {
  52025. this.onDisposeObservable.remove(this._onDisposeObserver);
  52026. }
  52027. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52028. },
  52029. enumerable: true,
  52030. configurable: true
  52031. });
  52032. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  52033. /**
  52034. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  52035. */
  52036. get: function () {
  52037. return this._isAnimationSheetEnabled;
  52038. },
  52039. enumerable: true,
  52040. configurable: true
  52041. });
  52042. Object.defineProperty(ParticleSystem.prototype, "particles", {
  52043. //end of Sub-emitter
  52044. /**
  52045. * Gets the current list of active particles
  52046. */
  52047. get: function () {
  52048. return this._particles;
  52049. },
  52050. enumerable: true,
  52051. configurable: true
  52052. });
  52053. /**
  52054. * Returns the string "ParticleSystem"
  52055. * @returns a string containing the class name
  52056. */
  52057. ParticleSystem.prototype.getClassName = function () {
  52058. return "ParticleSystem";
  52059. };
  52060. ParticleSystem.prototype._createIndexBuffer = function () {
  52061. var indices = [];
  52062. var index = 0;
  52063. for (var count = 0; count < this._capacity; count++) {
  52064. indices.push(index);
  52065. indices.push(index + 1);
  52066. indices.push(index + 2);
  52067. indices.push(index);
  52068. indices.push(index + 2);
  52069. indices.push(index + 3);
  52070. index += 4;
  52071. }
  52072. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  52073. };
  52074. /**
  52075. * Gets the maximum number of particles active at the same time.
  52076. * @returns The max number of active particles.
  52077. */
  52078. ParticleSystem.prototype.getCapacity = function () {
  52079. return this._capacity;
  52080. };
  52081. /**
  52082. * Gets Wether there are still active particles in the system.
  52083. * @returns True if it is alive, otherwise false.
  52084. */
  52085. ParticleSystem.prototype.isAlive = function () {
  52086. return this._alive;
  52087. };
  52088. /**
  52089. * Gets Wether the system has been started.
  52090. * @returns True if it has been started, otherwise false.
  52091. */
  52092. ParticleSystem.prototype.isStarted = function () {
  52093. return this._started;
  52094. };
  52095. /**
  52096. * Starts the particle system and begins to emit.
  52097. */
  52098. ParticleSystem.prototype.start = function () {
  52099. this._started = true;
  52100. this._stopped = false;
  52101. this._actualFrame = 0;
  52102. if (this.subEmitters && this.subEmitters.length != 0) {
  52103. this.activeSubSystems = new Array();
  52104. }
  52105. };
  52106. /**
  52107. * Stops the particle system.
  52108. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  52109. */
  52110. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  52111. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  52112. this._stopped = true;
  52113. if (stopSubEmitters) {
  52114. this._stopSubEmitters();
  52115. }
  52116. };
  52117. // animation sheet
  52118. /**
  52119. * Remove all active particles
  52120. */
  52121. ParticleSystem.prototype.reset = function () {
  52122. this._stockParticles = [];
  52123. this._particles = [];
  52124. };
  52125. /**
  52126. * @ignore (for internal use only)
  52127. */
  52128. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  52129. var offset = index * this._vertexBufferSize;
  52130. this._vertexData[offset] = particle.position.x;
  52131. this._vertexData[offset + 1] = particle.position.y;
  52132. this._vertexData[offset + 2] = particle.position.z;
  52133. this._vertexData[offset + 3] = particle.color.r;
  52134. this._vertexData[offset + 4] = particle.color.g;
  52135. this._vertexData[offset + 5] = particle.color.b;
  52136. this._vertexData[offset + 6] = particle.color.a;
  52137. this._vertexData[offset + 7] = particle.angle;
  52138. this._vertexData[offset + 8] = particle.size;
  52139. this._vertexData[offset + 9] = offsetX;
  52140. this._vertexData[offset + 10] = offsetY;
  52141. };
  52142. /**
  52143. * @ignore (for internal use only)
  52144. */
  52145. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  52146. if (offsetX === 0)
  52147. offsetX = this._epsilon;
  52148. else if (offsetX === 1)
  52149. offsetX = 1 - this._epsilon;
  52150. if (offsetY === 0)
  52151. offsetY = this._epsilon;
  52152. else if (offsetY === 1)
  52153. offsetY = 1 - this._epsilon;
  52154. var offset = index * this._vertexBufferSize;
  52155. this._vertexData[offset] = particle.position.x;
  52156. this._vertexData[offset + 1] = particle.position.y;
  52157. this._vertexData[offset + 2] = particle.position.z;
  52158. this._vertexData[offset + 3] = particle.color.r;
  52159. this._vertexData[offset + 4] = particle.color.g;
  52160. this._vertexData[offset + 5] = particle.color.b;
  52161. this._vertexData[offset + 6] = particle.color.a;
  52162. this._vertexData[offset + 7] = particle.angle;
  52163. this._vertexData[offset + 8] = particle.size;
  52164. this._vertexData[offset + 9] = offsetX;
  52165. this._vertexData[offset + 10] = offsetY;
  52166. this._vertexData[offset + 11] = particle.cellIndex;
  52167. };
  52168. ParticleSystem.prototype._stopSubEmitters = function () {
  52169. if (!this.activeSubSystems) {
  52170. return;
  52171. }
  52172. this.activeSubSystems.forEach(function (subSystem) {
  52173. subSystem.stop(true);
  52174. });
  52175. this.activeSubSystems = new Array();
  52176. };
  52177. ParticleSystem.prototype._removeFromRoot = function () {
  52178. if (!this._rootParticleSystem) {
  52179. return;
  52180. }
  52181. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  52182. if (index !== -1) {
  52183. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  52184. }
  52185. };
  52186. // end of sub system methods
  52187. ParticleSystem.prototype._update = function (newParticles) {
  52188. // Update current
  52189. this._alive = this._particles.length > 0;
  52190. this.updateFunction(this._particles);
  52191. // Add new ones
  52192. var worldMatrix;
  52193. if (this.emitter.position) {
  52194. var emitterMesh = this.emitter;
  52195. worldMatrix = emitterMesh.getWorldMatrix();
  52196. }
  52197. else {
  52198. var emitterPosition = this.emitter;
  52199. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52200. }
  52201. var particle;
  52202. for (var index = 0; index < newParticles; index++) {
  52203. if (this._particles.length === this._capacity) {
  52204. break;
  52205. }
  52206. particle = this._createParticle();
  52207. this._particles.push(particle);
  52208. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  52209. if (this.startPositionFunction) {
  52210. this.startPositionFunction(worldMatrix, particle.position, particle);
  52211. }
  52212. else {
  52213. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52214. }
  52215. if (this.startDirectionFunction) {
  52216. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52217. }
  52218. else {
  52219. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52220. }
  52221. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52222. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52223. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52224. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52225. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52226. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52227. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52228. }
  52229. };
  52230. ParticleSystem.prototype._getEffect = function () {
  52231. if (this._customEffect) {
  52232. return this._customEffect;
  52233. }
  52234. ;
  52235. var defines = [];
  52236. if (this._scene.clipPlane) {
  52237. defines.push("#define CLIPPLANE");
  52238. }
  52239. if (this._isAnimationSheetEnabled) {
  52240. defines.push("#define ANIMATESHEET");
  52241. }
  52242. // Effect
  52243. var join = defines.join("\n");
  52244. if (this._cachedDefines !== join) {
  52245. this._cachedDefines = join;
  52246. var attributesNamesOrOptions;
  52247. var effectCreationOption;
  52248. if (this._isAnimationSheetEnabled) {
  52249. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52250. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52251. }
  52252. else {
  52253. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52254. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52255. }
  52256. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52257. }
  52258. return this._effect;
  52259. };
  52260. /**
  52261. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52262. */
  52263. ParticleSystem.prototype.animate = function () {
  52264. if (!this._started)
  52265. return;
  52266. var effect = this._getEffect();
  52267. // Check
  52268. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52269. return;
  52270. if (this._currentRenderId === this._scene.getRenderId()) {
  52271. return;
  52272. }
  52273. this._currentRenderId = this._scene.getRenderId();
  52274. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52275. // determine the number of particles we need to create
  52276. var newParticles;
  52277. if (this.manualEmitCount > -1) {
  52278. newParticles = this.manualEmitCount;
  52279. this._newPartsExcess = 0;
  52280. this.manualEmitCount = 0;
  52281. }
  52282. else {
  52283. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52284. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52285. }
  52286. if (this._newPartsExcess > 1.0) {
  52287. newParticles += this._newPartsExcess >> 0;
  52288. this._newPartsExcess -= this._newPartsExcess >> 0;
  52289. }
  52290. this._alive = false;
  52291. if (!this._stopped) {
  52292. this._actualFrame += this._scaledUpdateSpeed;
  52293. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52294. this.stop();
  52295. }
  52296. else {
  52297. newParticles = 0;
  52298. }
  52299. this._update(newParticles);
  52300. // Stopped?
  52301. if (this._stopped) {
  52302. if (!this._alive) {
  52303. this._started = false;
  52304. if (this.onAnimationEnd) {
  52305. this.onAnimationEnd();
  52306. }
  52307. if (this.disposeOnStop) {
  52308. this._scene._toBeDisposed.push(this);
  52309. }
  52310. }
  52311. }
  52312. // Animation sheet
  52313. if (this._isAnimationSheetEnabled) {
  52314. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52315. }
  52316. else {
  52317. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52318. }
  52319. // Update VBO
  52320. var offset = 0;
  52321. for (var index = 0; index < this._particles.length; index++) {
  52322. var particle = this._particles[index];
  52323. this._appendParticleVertexes(offset, particle);
  52324. offset += 4;
  52325. }
  52326. if (this._vertexBuffer) {
  52327. this._vertexBuffer.update(this._vertexData);
  52328. }
  52329. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52330. this.stop();
  52331. }
  52332. };
  52333. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52334. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52335. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52336. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52337. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52338. };
  52339. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52340. this._appendParticleVertex(offset++, particle, 0, 0);
  52341. this._appendParticleVertex(offset++, particle, 1, 0);
  52342. this._appendParticleVertex(offset++, particle, 1, 1);
  52343. this._appendParticleVertex(offset++, particle, 0, 1);
  52344. };
  52345. /**
  52346. * Rebuilds the particle system.
  52347. */
  52348. ParticleSystem.prototype.rebuild = function () {
  52349. this._createIndexBuffer();
  52350. if (this._vertexBuffer) {
  52351. this._vertexBuffer._rebuild();
  52352. }
  52353. };
  52354. /**
  52355. * Is this system ready to be used/rendered
  52356. * @return true if the system is ready
  52357. */
  52358. ParticleSystem.prototype.isReady = function () {
  52359. var effect = this._getEffect();
  52360. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52361. return false;
  52362. }
  52363. return true;
  52364. };
  52365. /**
  52366. * Renders the particle system in its current state.
  52367. * @returns the current number of particles
  52368. */
  52369. ParticleSystem.prototype.render = function () {
  52370. var effect = this._getEffect();
  52371. // Check
  52372. if (!this.isReady() || !this._particles.length) {
  52373. return 0;
  52374. }
  52375. var engine = this._scene.getEngine();
  52376. // Render
  52377. engine.enableEffect(effect);
  52378. engine.setState(false);
  52379. var viewMatrix = this._scene.getViewMatrix();
  52380. effect.setTexture("diffuseSampler", this.particleTexture);
  52381. effect.setMatrix("view", viewMatrix);
  52382. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52383. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52384. var baseSize = this.particleTexture.getBaseSize();
  52385. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52386. }
  52387. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52388. if (this._scene.clipPlane) {
  52389. var clipPlane = this._scene.clipPlane;
  52390. var invView = viewMatrix.clone();
  52391. invView.invert();
  52392. effect.setMatrix("invView", invView);
  52393. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52394. }
  52395. // VBOs
  52396. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52397. // Draw order
  52398. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52399. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52400. }
  52401. else {
  52402. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52403. }
  52404. if (this.forceDepthWrite) {
  52405. engine.setDepthWrite(true);
  52406. }
  52407. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52408. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52409. return this._particles.length;
  52410. };
  52411. /**
  52412. * Disposes the particle system and free the associated resources
  52413. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52414. */
  52415. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52416. if (disposeTexture === void 0) { disposeTexture = true; }
  52417. if (this._vertexBuffer) {
  52418. this._vertexBuffer.dispose();
  52419. this._vertexBuffer = null;
  52420. }
  52421. if (this._indexBuffer) {
  52422. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52423. this._indexBuffer = null;
  52424. }
  52425. if (disposeTexture && this.particleTexture) {
  52426. this.particleTexture.dispose();
  52427. this.particleTexture = null;
  52428. }
  52429. this._removeFromRoot();
  52430. // Remove from scene
  52431. var index = this._scene.particleSystems.indexOf(this);
  52432. if (index > -1) {
  52433. this._scene.particleSystems.splice(index, 1);
  52434. }
  52435. // Callback
  52436. this.onDisposeObservable.notifyObservers(this);
  52437. this.onDisposeObservable.clear();
  52438. };
  52439. /**
  52440. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52441. * @param radius The radius of the sphere to emit from
  52442. * @returns the emitter
  52443. */
  52444. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52445. if (radius === void 0) { radius = 1; }
  52446. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52447. this.particleEmitterType = particleEmitter;
  52448. return particleEmitter;
  52449. };
  52450. /**
  52451. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52452. * @param radius The radius of the sphere to emit from
  52453. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52454. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52455. * @returns the emitter
  52456. */
  52457. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52458. if (radius === void 0) { radius = 1; }
  52459. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52460. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52461. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52462. this.particleEmitterType = particleEmitter;
  52463. return particleEmitter;
  52464. };
  52465. /**
  52466. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52467. * @param radius The radius of the cone to emit from
  52468. * @param angle The base angle of the cone
  52469. * @returns the emitter
  52470. */
  52471. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52472. if (radius === void 0) { radius = 1; }
  52473. if (angle === void 0) { angle = Math.PI / 4; }
  52474. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52475. this.particleEmitterType = particleEmitter;
  52476. return particleEmitter;
  52477. };
  52478. // 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.
  52479. /**
  52480. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52481. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52482. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52483. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52484. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52485. * @returns the emitter
  52486. */
  52487. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52488. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52489. this.particleEmitterType = particleEmitter;
  52490. this.direction1 = direction1;
  52491. this.direction2 = direction2;
  52492. this.minEmitBox = minEmitBox;
  52493. this.maxEmitBox = maxEmitBox;
  52494. return particleEmitter;
  52495. };
  52496. // Clone
  52497. /**
  52498. * Clones the particle system.
  52499. * @param name The name of the cloned object
  52500. * @param newEmitter The new emitter to use
  52501. * @returns the cloned particle system
  52502. */
  52503. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52504. var custom = null;
  52505. var program = null;
  52506. if (this.customShader != null) {
  52507. program = this.customShader;
  52508. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52509. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52510. }
  52511. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52512. result.customShader = program;
  52513. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52514. if (newEmitter === undefined) {
  52515. newEmitter = this.emitter;
  52516. }
  52517. result.emitter = newEmitter;
  52518. if (this.particleTexture) {
  52519. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52520. }
  52521. if (!this.preventAutoStart) {
  52522. result.start();
  52523. }
  52524. return result;
  52525. };
  52526. /**
  52527. * Serializes the particle system to a JSON object.
  52528. * @returns the JSON object
  52529. */
  52530. ParticleSystem.prototype.serialize = function () {
  52531. var serializationObject = {};
  52532. serializationObject.name = this.name;
  52533. serializationObject.id = this.id;
  52534. // Emitter
  52535. if (this.emitter.position) {
  52536. var emitterMesh = this.emitter;
  52537. serializationObject.emitterId = emitterMesh.id;
  52538. }
  52539. else {
  52540. var emitterPosition = this.emitter;
  52541. serializationObject.emitter = emitterPosition.asArray();
  52542. }
  52543. serializationObject.capacity = this.getCapacity();
  52544. if (this.particleTexture) {
  52545. serializationObject.textureName = this.particleTexture.name;
  52546. }
  52547. // Animations
  52548. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52549. // Particle system
  52550. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52551. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52552. serializationObject.minSize = this.minSize;
  52553. serializationObject.maxSize = this.maxSize;
  52554. serializationObject.minEmitPower = this.minEmitPower;
  52555. serializationObject.maxEmitPower = this.maxEmitPower;
  52556. serializationObject.minLifeTime = this.minLifeTime;
  52557. serializationObject.maxLifeTime = this.maxLifeTime;
  52558. serializationObject.emitRate = this.emitRate;
  52559. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52560. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52561. serializationObject.gravity = this.gravity.asArray();
  52562. serializationObject.direction1 = this.direction1.asArray();
  52563. serializationObject.direction2 = this.direction2.asArray();
  52564. serializationObject.color1 = this.color1.asArray();
  52565. serializationObject.color2 = this.color2.asArray();
  52566. serializationObject.colorDead = this.colorDead.asArray();
  52567. serializationObject.updateSpeed = this.updateSpeed;
  52568. serializationObject.targetStopDuration = this.targetStopDuration;
  52569. serializationObject.textureMask = this.textureMask.asArray();
  52570. serializationObject.blendMode = this.blendMode;
  52571. serializationObject.customShader = this.customShader;
  52572. serializationObject.preventAutoStart = this.preventAutoStart;
  52573. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52574. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52575. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52576. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52577. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52578. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52579. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52580. // Emitter
  52581. if (this.particleEmitterType) {
  52582. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52583. }
  52584. return serializationObject;
  52585. };
  52586. /**
  52587. * Parses a JSON object to create a particle system.
  52588. * @param parsedParticleSystem The JSON object to parse
  52589. * @param scene The scene to create the particle system in
  52590. * @param rootUrl The root url to use to load external dependencies like texture
  52591. * @returns the Parsed particle system
  52592. */
  52593. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52594. var name = parsedParticleSystem.name;
  52595. var custom = null;
  52596. var program = null;
  52597. if (parsedParticleSystem.customShader) {
  52598. program = parsedParticleSystem.customShader;
  52599. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52600. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52601. }
  52602. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52603. particleSystem.customShader = program;
  52604. if (parsedParticleSystem.id) {
  52605. particleSystem.id = parsedParticleSystem.id;
  52606. }
  52607. // Auto start
  52608. if (parsedParticleSystem.preventAutoStart) {
  52609. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52610. }
  52611. // Texture
  52612. if (parsedParticleSystem.textureName) {
  52613. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52614. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52615. }
  52616. // Emitter
  52617. if (parsedParticleSystem.emitterId) {
  52618. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52619. }
  52620. else {
  52621. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52622. }
  52623. // Animations
  52624. if (parsedParticleSystem.animations) {
  52625. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52626. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52627. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52628. }
  52629. }
  52630. if (parsedParticleSystem.autoAnimate) {
  52631. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52632. }
  52633. // Particle system
  52634. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52635. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52636. particleSystem.minSize = parsedParticleSystem.minSize;
  52637. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52638. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52639. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52640. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52641. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52642. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52643. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52644. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52645. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52646. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52647. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52648. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52649. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52650. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52651. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52652. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52653. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52654. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52655. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52656. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52657. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52658. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52659. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52660. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52661. if (!particleSystem.preventAutoStart) {
  52662. particleSystem.start();
  52663. }
  52664. return particleSystem;
  52665. };
  52666. /**
  52667. * Source color is added to the destination color without alpha affecting the result.
  52668. */
  52669. ParticleSystem.BLENDMODE_ONEONE = 0;
  52670. /**
  52671. * Blend current color and particle color using particle’s alpha.
  52672. */
  52673. ParticleSystem.BLENDMODE_STANDARD = 1;
  52674. return ParticleSystem;
  52675. }());
  52676. BABYLON.ParticleSystem = ParticleSystem;
  52677. })(BABYLON || (BABYLON = {}));
  52678. //# sourceMappingURL=babylon.particleSystem.js.map
  52679. "use strict";
  52680. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52681. "use strict";
  52682. var BABYLON;
  52683. (function (BABYLON) {
  52684. /**
  52685. * Particle emitter emitting particles from the inside of a box.
  52686. * It emits the particles randomly between 2 given directions.
  52687. */
  52688. var BoxParticleEmitter = /** @class */ (function () {
  52689. /**
  52690. * Creates a new instance of @see BoxParticleEmitter
  52691. */
  52692. function BoxParticleEmitter() {
  52693. /**
  52694. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52695. */
  52696. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52697. /**
  52698. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52699. */
  52700. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52701. /**
  52702. * 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.
  52703. */
  52704. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52705. /**
  52706. * 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.
  52707. */
  52708. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52709. }
  52710. /**
  52711. * Called by the particle System when the direction is computed for the created particle.
  52712. * @param emitPower is the power of the particle (speed)
  52713. * @param worldMatrix is the world matrix of the particle system
  52714. * @param directionToUpdate is the direction vector to update with the result
  52715. * @param particle is the particle we are computed the direction for
  52716. */
  52717. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52718. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52719. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52720. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52721. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52722. };
  52723. /**
  52724. * Called by the particle System when the position is computed for the created particle.
  52725. * @param worldMatrix is the world matrix of the particle system
  52726. * @param positionToUpdate is the position vector to update with the result
  52727. * @param particle is the particle we are computed the position for
  52728. */
  52729. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52730. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52731. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52732. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52733. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52734. };
  52735. /**
  52736. * Clones the current emitter and returns a copy of it
  52737. * @returns the new emitter
  52738. */
  52739. BoxParticleEmitter.prototype.clone = function () {
  52740. var newOne = new BoxParticleEmitter();
  52741. BABYLON.Tools.DeepCopy(this, newOne);
  52742. return newOne;
  52743. };
  52744. /**
  52745. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52746. * @param effect defines the update shader
  52747. */
  52748. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52749. effect.setVector3("direction1", this.direction1);
  52750. effect.setVector3("direction2", this.direction2);
  52751. effect.setVector3("minEmitBox", this.minEmitBox);
  52752. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52753. };
  52754. /**
  52755. * Returns a string to use to update the GPU particles update shader
  52756. * @returns a string containng the defines string
  52757. */
  52758. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52759. return "#define BOXEMITTER";
  52760. };
  52761. /**
  52762. * Returns the string "BoxEmitter"
  52763. * @returns a string containing the class name
  52764. */
  52765. BoxParticleEmitter.prototype.getClassName = function () {
  52766. return "BoxEmitter";
  52767. };
  52768. /**
  52769. * Serializes the particle system to a JSON object.
  52770. * @returns the JSON object
  52771. */
  52772. BoxParticleEmitter.prototype.serialize = function () {
  52773. var serializationObject = {};
  52774. serializationObject.type = this.getClassName();
  52775. serializationObject.direction1 = this.direction1.asArray();
  52776. ;
  52777. serializationObject.direction2 = this.direction2.asArray();
  52778. ;
  52779. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52780. ;
  52781. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52782. ;
  52783. return serializationObject;
  52784. };
  52785. /**
  52786. * Parse properties from a JSON object
  52787. * @param serializationObject defines the JSON object
  52788. */
  52789. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52790. this.direction1.copyFrom(serializationObject.direction1);
  52791. this.direction2.copyFrom(serializationObject.direction2);
  52792. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52793. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52794. };
  52795. return BoxParticleEmitter;
  52796. }());
  52797. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52798. })(BABYLON || (BABYLON = {}));
  52799. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52800. "use strict";
  52801. var BABYLON;
  52802. (function (BABYLON) {
  52803. /**
  52804. * Particle emitter emitting particles from the inside of a cone.
  52805. * It emits the particles alongside the cone volume from the base to the particle.
  52806. * The emission direction might be randomized.
  52807. */
  52808. var ConeParticleEmitter = /** @class */ (function () {
  52809. /**
  52810. * Creates a new instance of @see ConeParticleEmitter
  52811. * @param radius the radius of the emission cone (1 by default)
  52812. * @param angles the cone base angle (PI by default)
  52813. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52814. */
  52815. function ConeParticleEmitter(radius,
  52816. /**
  52817. * The radius of the emission cone.
  52818. */
  52819. angle,
  52820. /**
  52821. * The cone base angle.
  52822. */
  52823. directionRandomizer) {
  52824. if (radius === void 0) { radius = 1; }
  52825. if (angle === void 0) { angle = Math.PI; }
  52826. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52827. this.angle = angle;
  52828. this.directionRandomizer = directionRandomizer;
  52829. this.radius = radius;
  52830. }
  52831. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52832. /**
  52833. * Gets the radius of the emission cone.
  52834. */
  52835. get: function () {
  52836. return this._radius;
  52837. },
  52838. /**
  52839. * Sets the radius of the emission cone.
  52840. */
  52841. set: function (value) {
  52842. this._radius = value;
  52843. if (this.angle !== 0) {
  52844. this._height = value / Math.tan(this.angle / 2);
  52845. }
  52846. else {
  52847. this._height = 1;
  52848. }
  52849. },
  52850. enumerable: true,
  52851. configurable: true
  52852. });
  52853. /**
  52854. * Called by the particle System when the direction is computed for the created particle.
  52855. * @param emitPower is the power of the particle (speed)
  52856. * @param worldMatrix is the world matrix of the particle system
  52857. * @param directionToUpdate is the direction vector to update with the result
  52858. * @param particle is the particle we are computed the direction for
  52859. */
  52860. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52861. if (this.angle === 0) {
  52862. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52863. }
  52864. else {
  52865. // measure the direction Vector from the emitter to the particle.
  52866. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52867. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52868. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52869. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52870. direction.x += randX;
  52871. direction.y += randY;
  52872. direction.z += randZ;
  52873. direction.normalize();
  52874. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52875. }
  52876. };
  52877. /**
  52878. * Called by the particle System when the position is computed for the created particle.
  52879. * @param worldMatrix is the world matrix of the particle system
  52880. * @param positionToUpdate is the position vector to update with the result
  52881. * @param particle is the particle we are computed the position for
  52882. */
  52883. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52884. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52885. var h = BABYLON.Scalar.RandomRange(0, 1);
  52886. // Better distribution in a cone at normal angles.
  52887. h = 1 - h * h;
  52888. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52889. radius = radius * h;
  52890. var randX = radius * Math.sin(s);
  52891. var randZ = radius * Math.cos(s);
  52892. var randY = h * this._height;
  52893. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52894. };
  52895. /**
  52896. * Clones the current emitter and returns a copy of it
  52897. * @returns the new emitter
  52898. */
  52899. ConeParticleEmitter.prototype.clone = function () {
  52900. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52901. BABYLON.Tools.DeepCopy(this, newOne);
  52902. return newOne;
  52903. };
  52904. /**
  52905. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52906. * @param effect defines the update shader
  52907. */
  52908. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52909. effect.setFloat("radius", this.radius);
  52910. effect.setFloat("angle", this.angle);
  52911. effect.setFloat("height", this._height);
  52912. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52913. };
  52914. /**
  52915. * Returns a string to use to update the GPU particles update shader
  52916. * @returns a string containng the defines string
  52917. */
  52918. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52919. return "#define CONEEMITTER";
  52920. };
  52921. /**
  52922. * Returns the string "BoxEmitter"
  52923. * @returns a string containing the class name
  52924. */
  52925. ConeParticleEmitter.prototype.getClassName = function () {
  52926. return "ConeEmitter";
  52927. };
  52928. /**
  52929. * Serializes the particle system to a JSON object.
  52930. * @returns the JSON object
  52931. */
  52932. ConeParticleEmitter.prototype.serialize = function () {
  52933. var serializationObject = {};
  52934. serializationObject.type = this.getClassName();
  52935. serializationObject.radius = this.radius;
  52936. serializationObject.angle = this.angle;
  52937. serializationObject.directionRandomizer = this.directionRandomizer;
  52938. return serializationObject;
  52939. };
  52940. /**
  52941. * Parse properties from a JSON object
  52942. * @param serializationObject defines the JSON object
  52943. */
  52944. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52945. this.radius = serializationObject.radius;
  52946. this.angle = serializationObject.angle;
  52947. this.directionRandomizer = serializationObject.directionRandomizer;
  52948. };
  52949. return ConeParticleEmitter;
  52950. }());
  52951. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52952. })(BABYLON || (BABYLON = {}));
  52953. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52954. "use strict";
  52955. var BABYLON;
  52956. (function (BABYLON) {
  52957. /**
  52958. * Particle emitter emitting particles from the inside of a sphere.
  52959. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52960. */
  52961. var SphereParticleEmitter = /** @class */ (function () {
  52962. /**
  52963. * Creates a new instance of @see SphereParticleEmitter
  52964. * @param radius the radius of the emission sphere (1 by default)
  52965. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52966. */
  52967. function SphereParticleEmitter(
  52968. /**
  52969. * The radius of the emission sphere.
  52970. */
  52971. radius,
  52972. /**
  52973. * How much to randomize the particle direction [0-1].
  52974. */
  52975. directionRandomizer) {
  52976. if (radius === void 0) { radius = 1; }
  52977. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52978. this.radius = radius;
  52979. this.directionRandomizer = directionRandomizer;
  52980. }
  52981. /**
  52982. * Called by the particle System when the direction is computed for the created particle.
  52983. * @param emitPower is the power of the particle (speed)
  52984. * @param worldMatrix is the world matrix of the particle system
  52985. * @param directionToUpdate is the direction vector to update with the result
  52986. * @param particle is the particle we are computed the direction for
  52987. */
  52988. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52989. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52990. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52991. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52992. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52993. direction.x += randX;
  52994. direction.y += randY;
  52995. direction.z += randZ;
  52996. direction.normalize();
  52997. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52998. };
  52999. /**
  53000. * Called by the particle System when the position is computed for the created particle.
  53001. * @param worldMatrix is the world matrix of the particle system
  53002. * @param positionToUpdate is the position vector to update with the result
  53003. * @param particle is the particle we are computed the position for
  53004. */
  53005. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  53006. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  53007. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  53008. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  53009. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  53010. var randY = randRadius * Math.cos(theta);
  53011. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  53012. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  53013. };
  53014. /**
  53015. * Clones the current emitter and returns a copy of it
  53016. * @returns the new emitter
  53017. */
  53018. SphereParticleEmitter.prototype.clone = function () {
  53019. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  53020. BABYLON.Tools.DeepCopy(this, newOne);
  53021. return newOne;
  53022. };
  53023. /**
  53024. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53025. * @param effect defines the update shader
  53026. */
  53027. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  53028. effect.setFloat("radius", this.radius);
  53029. effect.setFloat("directionRandomizer", this.directionRandomizer);
  53030. };
  53031. /**
  53032. * Returns a string to use to update the GPU particles update shader
  53033. * @returns a string containng the defines string
  53034. */
  53035. SphereParticleEmitter.prototype.getEffectDefines = function () {
  53036. return "#define SPHEREEMITTER";
  53037. };
  53038. /**
  53039. * Returns the string "SphereParticleEmitter"
  53040. * @returns a string containing the class name
  53041. */
  53042. SphereParticleEmitter.prototype.getClassName = function () {
  53043. return "SphereParticleEmitter";
  53044. };
  53045. /**
  53046. * Serializes the particle system to a JSON object.
  53047. * @returns the JSON object
  53048. */
  53049. SphereParticleEmitter.prototype.serialize = function () {
  53050. var serializationObject = {};
  53051. serializationObject.type = this.getClassName();
  53052. serializationObject.radius = this.radius;
  53053. serializationObject.directionRandomizer = this.directionRandomizer;
  53054. return serializationObject;
  53055. };
  53056. /**
  53057. * Parse properties from a JSON object
  53058. * @param serializationObject defines the JSON object
  53059. */
  53060. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  53061. this.radius = serializationObject.radius;
  53062. this.directionRandomizer = serializationObject.directionRandomizer;
  53063. };
  53064. return SphereParticleEmitter;
  53065. }());
  53066. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  53067. /**
  53068. * Particle emitter emitting particles from the inside of a sphere.
  53069. * It emits the particles randomly between two vectors.
  53070. */
  53071. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  53072. __extends(SphereDirectedParticleEmitter, _super);
  53073. /**
  53074. * Creates a new instance of @see SphereDirectedParticleEmitter
  53075. * @param radius the radius of the emission sphere (1 by default)
  53076. * @param direction1 the min limit of the emission direction (up vector by default)
  53077. * @param direction2 the max limit of the emission direction (up vector by default)
  53078. */
  53079. function SphereDirectedParticleEmitter(radius,
  53080. /**
  53081. * The min limit of the emission direction.
  53082. */
  53083. direction1,
  53084. /**
  53085. * The max limit of the emission direction.
  53086. */
  53087. direction2) {
  53088. if (radius === void 0) { radius = 1; }
  53089. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  53090. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  53091. var _this = _super.call(this, radius) || this;
  53092. _this.direction1 = direction1;
  53093. _this.direction2 = direction2;
  53094. return _this;
  53095. }
  53096. /**
  53097. * Called by the particle System when the direction is computed for the created particle.
  53098. * @param emitPower is the power of the particle (speed)
  53099. * @param worldMatrix is the world matrix of the particle system
  53100. * @param directionToUpdate is the direction vector to update with the result
  53101. * @param particle is the particle we are computed the direction for
  53102. */
  53103. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53104. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  53105. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  53106. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  53107. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  53108. };
  53109. /**
  53110. * Clones the current emitter and returns a copy of it
  53111. * @returns the new emitter
  53112. */
  53113. SphereDirectedParticleEmitter.prototype.clone = function () {
  53114. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  53115. BABYLON.Tools.DeepCopy(this, newOne);
  53116. return newOne;
  53117. };
  53118. /**
  53119. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53120. * @param effect defines the update shader
  53121. */
  53122. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  53123. effect.setFloat("radius", this.radius);
  53124. effect.setVector3("direction1", this.direction1);
  53125. effect.setVector3("direction2", this.direction2);
  53126. };
  53127. /**
  53128. * Returns a string to use to update the GPU particles update shader
  53129. * @returns a string containng the defines string
  53130. */
  53131. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  53132. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  53133. };
  53134. /**
  53135. * Returns the string "SphereDirectedParticleEmitter"
  53136. * @returns a string containing the class name
  53137. */
  53138. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  53139. return "SphereDirectedParticleEmitter";
  53140. };
  53141. /**
  53142. * Serializes the particle system to a JSON object.
  53143. * @returns the JSON object
  53144. */
  53145. SphereDirectedParticleEmitter.prototype.serialize = function () {
  53146. var serializationObject = _super.prototype.serialize.call(this);
  53147. ;
  53148. serializationObject.direction1 = this.direction1.asArray();
  53149. ;
  53150. serializationObject.direction2 = this.direction2.asArray();
  53151. ;
  53152. return serializationObject;
  53153. };
  53154. /**
  53155. * Parse properties from a JSON object
  53156. * @param serializationObject defines the JSON object
  53157. */
  53158. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  53159. _super.prototype.parse.call(this, serializationObject);
  53160. this.direction1.copyFrom(serializationObject.direction1);
  53161. this.direction2.copyFrom(serializationObject.direction2);
  53162. };
  53163. return SphereDirectedParticleEmitter;
  53164. }(SphereParticleEmitter));
  53165. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  53166. })(BABYLON || (BABYLON = {}));
  53167. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  53168. "use strict";
  53169. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53170. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53171. s = arguments[i];
  53172. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53173. t[p] = s[p];
  53174. }
  53175. return t;
  53176. };
  53177. var BABYLON;
  53178. (function (BABYLON) {
  53179. /**
  53180. * This represents a GPU particle system in Babylon
  53181. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  53182. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  53183. */
  53184. var GPUParticleSystem = /** @class */ (function () {
  53185. /**
  53186. * Instantiates a GPU particle system.
  53187. * 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.
  53188. * @param name The name of the particle system
  53189. * @param capacity The max number of particles alive at the same time
  53190. * @param scene The scene the particle system belongs to
  53191. */
  53192. function GPUParticleSystem(name, options, scene) {
  53193. /**
  53194. * The emitter represents the Mesh or position we are attaching the particle system to.
  53195. */
  53196. this.emitter = null;
  53197. /**
  53198. * The rendering group used by the Particle system to chose when to render.
  53199. */
  53200. this.renderingGroupId = 0;
  53201. /**
  53202. * The layer mask we are rendering the particles through.
  53203. */
  53204. this.layerMask = 0x0FFFFFFF;
  53205. this._targetIndex = 0;
  53206. this._currentRenderId = -1;
  53207. this._started = false;
  53208. this._stopped = false;
  53209. this._timeDelta = 0;
  53210. this._attributesStrideSize = 14;
  53211. this._actualFrame = 0;
  53212. /**
  53213. * List of animations used by the particle system.
  53214. */
  53215. this.animations = [];
  53216. /**
  53217. * An event triggered when the system is disposed.
  53218. */
  53219. this.onDisposeObservable = new BABYLON.Observable();
  53220. /**
  53221. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53222. */
  53223. this.updateSpeed = 0.01;
  53224. /**
  53225. * The amount of time the particle system is running (depends of the overall update speed).
  53226. */
  53227. this.targetStopDuration = 0;
  53228. /**
  53229. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53230. */
  53231. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53232. /**
  53233. * Minimum life time of emitting particles.
  53234. */
  53235. this.minLifeTime = 1;
  53236. /**
  53237. * Maximum life time of emitting particles.
  53238. */
  53239. this.maxLifeTime = 1;
  53240. /**
  53241. * Minimum Size of emitting particles.
  53242. */
  53243. this.minSize = 1;
  53244. /**
  53245. * Maximum Size of emitting particles.
  53246. */
  53247. this.maxSize = 1;
  53248. /**
  53249. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53250. */
  53251. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53252. /**
  53253. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53254. */
  53255. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53256. /**
  53257. * Color the particle will have at the end of its lifetime.
  53258. */
  53259. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53260. /**
  53261. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53262. */
  53263. this.emitRate = 100;
  53264. /**
  53265. * You can use gravity if you want to give an orientation to your particles.
  53266. */
  53267. this.gravity = BABYLON.Vector3.Zero();
  53268. /**
  53269. * Minimum power of emitting particles.
  53270. */
  53271. this.minEmitPower = 1;
  53272. /**
  53273. * Maximum power of emitting particles.
  53274. */
  53275. this.maxEmitPower = 1;
  53276. /**
  53277. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53278. * to override the particles.
  53279. */
  53280. this.forceDepthWrite = false;
  53281. this.id = name;
  53282. this.name = name;
  53283. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53284. this._engine = this._scene.getEngine();
  53285. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53286. this._capacity = fullOptions.capacity;
  53287. this._activeCount = fullOptions.capacity;
  53288. this._currentActiveCount = 0;
  53289. this._scene.particleSystems.push(this);
  53290. this._updateEffectOptions = {
  53291. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53292. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53293. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53294. uniformBuffersNames: [],
  53295. samplers: ["randomSampler"],
  53296. defines: "",
  53297. fallbacks: null,
  53298. onCompiled: null,
  53299. onError: null,
  53300. indexParameters: null,
  53301. maxSimultaneousLights: 0,
  53302. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53303. };
  53304. // Random data
  53305. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53306. var d = [];
  53307. for (var i = 0; i < maxTextureSize; ++i) {
  53308. d.push(Math.random());
  53309. d.push(Math.random());
  53310. d.push(Math.random());
  53311. d.push(Math.random());
  53312. }
  53313. 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);
  53314. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53315. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53316. this._randomTextureSize = maxTextureSize;
  53317. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53318. }
  53319. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53320. /**
  53321. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53322. */
  53323. get: function () {
  53324. if (!BABYLON.Engine.LastCreatedEngine) {
  53325. return false;
  53326. }
  53327. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53328. },
  53329. enumerable: true,
  53330. configurable: true
  53331. });
  53332. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53333. /**
  53334. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53335. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53336. */
  53337. get: function () {
  53338. if (this.particleEmitterType.direction1) {
  53339. return this.particleEmitterType.direction1;
  53340. }
  53341. return BABYLON.Vector3.Zero();
  53342. },
  53343. set: function (value) {
  53344. if (this.particleEmitterType.direction1) {
  53345. this.particleEmitterType.direction1 = value;
  53346. }
  53347. },
  53348. enumerable: true,
  53349. configurable: true
  53350. });
  53351. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53352. /**
  53353. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53354. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53355. */
  53356. get: function () {
  53357. if (this.particleEmitterType.direction2) {
  53358. return this.particleEmitterType.direction2;
  53359. }
  53360. return BABYLON.Vector3.Zero();
  53361. },
  53362. set: function (value) {
  53363. if (this.particleEmitterType.direction2) {
  53364. this.particleEmitterType.direction2 = value;
  53365. }
  53366. },
  53367. enumerable: true,
  53368. configurable: true
  53369. });
  53370. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53371. /**
  53372. * 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.
  53373. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53374. */
  53375. get: function () {
  53376. if (this.particleEmitterType.minEmitBox) {
  53377. return this.particleEmitterType.minEmitBox;
  53378. }
  53379. return BABYLON.Vector3.Zero();
  53380. },
  53381. set: function (value) {
  53382. if (this.particleEmitterType.minEmitBox) {
  53383. this.particleEmitterType.minEmitBox = value;
  53384. }
  53385. },
  53386. enumerable: true,
  53387. configurable: true
  53388. });
  53389. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53390. /**
  53391. * 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.
  53392. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53393. */
  53394. get: function () {
  53395. if (this.particleEmitterType.maxEmitBox) {
  53396. return this.particleEmitterType.maxEmitBox;
  53397. }
  53398. return BABYLON.Vector3.Zero();
  53399. },
  53400. set: function (value) {
  53401. if (this.particleEmitterType.maxEmitBox) {
  53402. this.particleEmitterType.maxEmitBox = value;
  53403. }
  53404. },
  53405. enumerable: true,
  53406. configurable: true
  53407. });
  53408. /**
  53409. * Gets the maximum number of particles active at the same time.
  53410. * @returns The max number of active particles.
  53411. */
  53412. GPUParticleSystem.prototype.getCapacity = function () {
  53413. return this._capacity;
  53414. };
  53415. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53416. /**
  53417. * Gets or set the number of active particles
  53418. */
  53419. get: function () {
  53420. return this._activeCount;
  53421. },
  53422. set: function (value) {
  53423. this._activeCount = Math.min(value, this._capacity);
  53424. },
  53425. enumerable: true,
  53426. configurable: true
  53427. });
  53428. /**
  53429. * Is this system ready to be used/rendered
  53430. * @return true if the system is ready
  53431. */
  53432. GPUParticleSystem.prototype.isReady = function () {
  53433. if (!this._updateEffect) {
  53434. this._recreateUpdateEffect();
  53435. this._recreateRenderEffect();
  53436. return false;
  53437. }
  53438. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53439. return false;
  53440. }
  53441. return true;
  53442. };
  53443. /**
  53444. * Gets Wether the system has been started.
  53445. * @returns True if it has been started, otherwise false.
  53446. */
  53447. GPUParticleSystem.prototype.isStarted = function () {
  53448. return this._started;
  53449. };
  53450. /**
  53451. * Starts the particle system and begins to emit.
  53452. */
  53453. GPUParticleSystem.prototype.start = function () {
  53454. this._started = true;
  53455. this._stopped = false;
  53456. };
  53457. /**
  53458. * Stops the particle system.
  53459. */
  53460. GPUParticleSystem.prototype.stop = function () {
  53461. this._stopped = true;
  53462. };
  53463. /**
  53464. * Remove all active particles
  53465. */
  53466. GPUParticleSystem.prototype.reset = function () {
  53467. this._releaseBuffers();
  53468. this._releaseVAOs();
  53469. this._currentActiveCount = 0;
  53470. this._targetIndex = 0;
  53471. };
  53472. /**
  53473. * Returns the string "GPUParticleSystem"
  53474. * @returns a string containing the class name
  53475. */
  53476. GPUParticleSystem.prototype.getClassName = function () {
  53477. return "GPUParticleSystem";
  53478. };
  53479. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53480. var updateVertexBuffers = {};
  53481. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53482. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53483. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53484. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53485. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53486. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53487. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53488. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53489. this._engine.bindArrayBuffer(null);
  53490. return vao;
  53491. };
  53492. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53493. var renderVertexBuffers = {};
  53494. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53495. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53496. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53497. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53498. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53499. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53500. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53501. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53502. this._engine.bindArrayBuffer(null);
  53503. return vao;
  53504. };
  53505. GPUParticleSystem.prototype._initialize = function (force) {
  53506. if (force === void 0) { force = false; }
  53507. if (this._buffer0 && !force) {
  53508. return;
  53509. }
  53510. var engine = this._scene.getEngine();
  53511. var data = new Array();
  53512. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53513. // position
  53514. data.push(0.0);
  53515. data.push(0.0);
  53516. data.push(0.0);
  53517. // Age and life
  53518. data.push(0.0); // create the particle as a dead one to create a new one at start
  53519. data.push(0.0);
  53520. // Seed
  53521. data.push(Math.random());
  53522. // Size
  53523. data.push(0.0);
  53524. // color
  53525. data.push(0.0);
  53526. data.push(0.0);
  53527. data.push(0.0);
  53528. data.push(0.0);
  53529. // direction
  53530. data.push(0.0);
  53531. data.push(0.0);
  53532. data.push(0.0);
  53533. }
  53534. // Sprite data
  53535. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53536. -0.5, 0.5, 0, 1,
  53537. -0.5, -0.5, 0, 0,
  53538. 0.5, -0.5, 1, 0]);
  53539. // Buffers
  53540. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53541. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53542. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53543. // Update VAO
  53544. this._updateVAO = [];
  53545. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53546. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53547. // Render VAO
  53548. this._renderVAO = [];
  53549. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53550. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53551. // Links
  53552. this._sourceBuffer = this._buffer0;
  53553. this._targetBuffer = this._buffer1;
  53554. };
  53555. /** @ignore */
  53556. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53557. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53558. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53559. return;
  53560. }
  53561. this._updateEffectOptions.defines = defines;
  53562. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53563. };
  53564. /** @ignore */
  53565. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53566. var defines = "";
  53567. if (this._scene.clipPlane) {
  53568. defines = "\n#define CLIPPLANE";
  53569. }
  53570. if (this._renderEffect && this._renderEffect.defines === defines) {
  53571. return;
  53572. }
  53573. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53574. };
  53575. /**
  53576. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53577. */
  53578. GPUParticleSystem.prototype.animate = function () {
  53579. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53580. this._actualFrame += this._timeDelta;
  53581. if (!this._stopped) {
  53582. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53583. this.stop();
  53584. }
  53585. }
  53586. };
  53587. /**
  53588. * Renders the particle system in its current state.
  53589. * @returns the current number of particles
  53590. */
  53591. GPUParticleSystem.prototype.render = function () {
  53592. if (!this._started) {
  53593. return 0;
  53594. }
  53595. this._recreateUpdateEffect();
  53596. this._recreateRenderEffect();
  53597. if (!this.isReady()) {
  53598. return 0;
  53599. }
  53600. if (this._currentRenderId === this._scene.getRenderId()) {
  53601. return 0;
  53602. }
  53603. this._currentRenderId = this._scene.getRenderId();
  53604. // Get everything ready to render
  53605. this._initialize();
  53606. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53607. // Enable update effect
  53608. this._engine.enableEffect(this._updateEffect);
  53609. this._engine.setState(false);
  53610. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53611. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53612. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53613. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53614. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53615. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53616. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53617. this._updateEffect.setDirectColor4("color1", this.color1);
  53618. this._updateEffect.setDirectColor4("color2", this.color2);
  53619. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53620. this._updateEffect.setVector3("gravity", this.gravity);
  53621. if (this.particleEmitterType) {
  53622. this.particleEmitterType.applyToShader(this._updateEffect);
  53623. }
  53624. var emitterWM;
  53625. if (this.emitter.position) {
  53626. var emitterMesh = this.emitter;
  53627. emitterWM = emitterMesh.getWorldMatrix();
  53628. }
  53629. else {
  53630. var emitterPosition = this.emitter;
  53631. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53632. }
  53633. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53634. // Bind source VAO
  53635. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53636. // Update
  53637. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53638. this._engine.setRasterizerState(false);
  53639. this._engine.beginTransformFeedback();
  53640. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53641. this._engine.endTransformFeedback();
  53642. this._engine.setRasterizerState(true);
  53643. this._engine.bindTransformFeedbackBuffer(null);
  53644. // Enable render effect
  53645. this._engine.enableEffect(this._renderEffect);
  53646. var viewMatrix = this._scene.getViewMatrix();
  53647. this._renderEffect.setMatrix("view", viewMatrix);
  53648. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53649. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53650. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53651. if (this._scene.clipPlane) {
  53652. var clipPlane = this._scene.clipPlane;
  53653. var invView = viewMatrix.clone();
  53654. invView.invert();
  53655. this._renderEffect.setMatrix("invView", invView);
  53656. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53657. }
  53658. // Draw order
  53659. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53660. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53661. }
  53662. else {
  53663. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53664. }
  53665. if (this.forceDepthWrite) {
  53666. this._engine.setDepthWrite(true);
  53667. }
  53668. // Bind source VAO
  53669. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53670. // Render
  53671. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53672. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53673. // Switch VAOs
  53674. this._targetIndex++;
  53675. if (this._targetIndex === 2) {
  53676. this._targetIndex = 0;
  53677. }
  53678. // Switch buffers
  53679. var tmpBuffer = this._sourceBuffer;
  53680. this._sourceBuffer = this._targetBuffer;
  53681. this._targetBuffer = tmpBuffer;
  53682. return this._currentActiveCount;
  53683. };
  53684. /**
  53685. * Rebuilds the particle system
  53686. */
  53687. GPUParticleSystem.prototype.rebuild = function () {
  53688. this._initialize(true);
  53689. };
  53690. GPUParticleSystem.prototype._releaseBuffers = function () {
  53691. if (this._buffer0) {
  53692. this._buffer0.dispose();
  53693. this._buffer0 = null;
  53694. }
  53695. if (this._buffer1) {
  53696. this._buffer1.dispose();
  53697. this._buffer1 = null;
  53698. }
  53699. if (this._spriteBuffer) {
  53700. this._spriteBuffer.dispose();
  53701. this._spriteBuffer = null;
  53702. }
  53703. };
  53704. GPUParticleSystem.prototype._releaseVAOs = function () {
  53705. if (!this._updateVAO) {
  53706. return;
  53707. }
  53708. for (var index = 0; index < this._updateVAO.length; index++) {
  53709. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53710. }
  53711. this._updateVAO = [];
  53712. for (var index = 0; index < this._renderVAO.length; index++) {
  53713. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53714. }
  53715. this._renderVAO = [];
  53716. };
  53717. /**
  53718. * Disposes the particle system and free the associated resources
  53719. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53720. */
  53721. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53722. if (disposeTexture === void 0) { disposeTexture = true; }
  53723. var index = this._scene.particleSystems.indexOf(this);
  53724. if (index > -1) {
  53725. this._scene.particleSystems.splice(index, 1);
  53726. }
  53727. this._releaseBuffers();
  53728. this._releaseVAOs();
  53729. if (this._randomTexture) {
  53730. this._randomTexture.dispose();
  53731. this._randomTexture = null;
  53732. }
  53733. if (disposeTexture && this.particleTexture) {
  53734. this.particleTexture.dispose();
  53735. this.particleTexture = null;
  53736. }
  53737. // Callback
  53738. this.onDisposeObservable.notifyObservers(this);
  53739. this.onDisposeObservable.clear();
  53740. };
  53741. /**
  53742. * Clones the particle system.
  53743. * @param name The name of the cloned object
  53744. * @param newEmitter The new emitter to use
  53745. * @returns the cloned particle system
  53746. */
  53747. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53748. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53749. BABYLON.Tools.DeepCopy(this, result);
  53750. if (newEmitter === undefined) {
  53751. newEmitter = this.emitter;
  53752. }
  53753. result.emitter = newEmitter;
  53754. if (this.particleTexture) {
  53755. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53756. }
  53757. return result;
  53758. };
  53759. /**
  53760. * Serializes the particle system to a JSON object.
  53761. * @returns the JSON object
  53762. */
  53763. GPUParticleSystem.prototype.serialize = function () {
  53764. var serializationObject = {};
  53765. serializationObject.name = this.name;
  53766. serializationObject.id = this.id;
  53767. // Emitter
  53768. if (this.emitter.position) {
  53769. var emitterMesh = this.emitter;
  53770. serializationObject.emitterId = emitterMesh.id;
  53771. }
  53772. else {
  53773. var emitterPosition = this.emitter;
  53774. serializationObject.emitter = emitterPosition.asArray();
  53775. }
  53776. serializationObject.capacity = this.getCapacity();
  53777. if (this.particleTexture) {
  53778. serializationObject.textureName = this.particleTexture.name;
  53779. }
  53780. // Animations
  53781. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53782. // Particle system
  53783. serializationObject.activeParticleCount = this.activeParticleCount;
  53784. serializationObject.randomTextureSize = this._randomTextureSize;
  53785. serializationObject.minSize = this.minSize;
  53786. serializationObject.maxSize = this.maxSize;
  53787. serializationObject.minEmitPower = this.minEmitPower;
  53788. serializationObject.maxEmitPower = this.maxEmitPower;
  53789. serializationObject.minLifeTime = this.minLifeTime;
  53790. serializationObject.maxLifeTime = this.maxLifeTime;
  53791. serializationObject.emitRate = this.emitRate;
  53792. serializationObject.gravity = this.gravity.asArray();
  53793. serializationObject.color1 = this.color1.asArray();
  53794. serializationObject.color2 = this.color2.asArray();
  53795. serializationObject.colorDead = this.colorDead.asArray();
  53796. serializationObject.updateSpeed = this.updateSpeed;
  53797. serializationObject.targetStopDuration = this.targetStopDuration;
  53798. serializationObject.blendMode = this.blendMode;
  53799. // Emitter
  53800. if (this.particleEmitterType) {
  53801. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53802. }
  53803. return serializationObject;
  53804. };
  53805. /**
  53806. * Parses a JSON object to create a GPU particle system.
  53807. * @param parsedParticleSystem The JSON object to parse
  53808. * @param scene The scene to create the particle system in
  53809. * @param rootUrl The root url to use to load external dependencies like texture
  53810. * @returns the parsed GPU particle system
  53811. */
  53812. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53813. var name = parsedParticleSystem.name;
  53814. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53815. if (parsedParticleSystem.id) {
  53816. particleSystem.id = parsedParticleSystem.id;
  53817. }
  53818. // Texture
  53819. if (parsedParticleSystem.textureName) {
  53820. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53821. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53822. }
  53823. // Emitter
  53824. if (parsedParticleSystem.emitterId) {
  53825. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53826. }
  53827. else {
  53828. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53829. }
  53830. // Animations
  53831. if (parsedParticleSystem.animations) {
  53832. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53833. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53834. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53835. }
  53836. }
  53837. // Particle system
  53838. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53839. particleSystem.minSize = parsedParticleSystem.minSize;
  53840. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53841. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53842. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53843. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53844. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53845. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53846. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53847. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53848. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53849. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53850. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53851. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53852. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53853. // Emitter
  53854. if (parsedParticleSystem.particleEmitterType) {
  53855. var emitterType = void 0;
  53856. switch (parsedParticleSystem.particleEmitterType.type) {
  53857. case "SphereEmitter":
  53858. emitterType = new BABYLON.SphereParticleEmitter();
  53859. break;
  53860. case "SphereDirectedParticleEmitter":
  53861. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53862. break;
  53863. case "ConeEmitter":
  53864. emitterType = new BABYLON.ConeParticleEmitter();
  53865. break;
  53866. case "BoxEmitter":
  53867. default:
  53868. emitterType = new BABYLON.BoxParticleEmitter();
  53869. break;
  53870. }
  53871. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53872. particleSystem.particleEmitterType = emitterType;
  53873. }
  53874. return particleSystem;
  53875. };
  53876. return GPUParticleSystem;
  53877. }());
  53878. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53879. })(BABYLON || (BABYLON = {}));
  53880. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53881. "use strict";
  53882. var BABYLON;
  53883. (function (BABYLON) {
  53884. /**
  53885. * Represents one particle of a solid particle system.
  53886. * @see SolidParticleSystem
  53887. */
  53888. var SolidParticle = /** @class */ (function () {
  53889. /**
  53890. * Creates a Solid Particle object.
  53891. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53892. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53893. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53894. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53895. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53896. * @param shapeId (integer) is the model shape identifier in the SPS.
  53897. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53898. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53899. */
  53900. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53901. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53902. /**
  53903. * particle global index
  53904. */
  53905. this.idx = 0;
  53906. /**
  53907. * The color of the particle
  53908. */
  53909. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53910. /**
  53911. * The world space position of the particle.
  53912. */
  53913. this.position = BABYLON.Vector3.Zero();
  53914. /**
  53915. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53916. */
  53917. this.rotation = BABYLON.Vector3.Zero();
  53918. /**
  53919. * The scaling of the particle.
  53920. */
  53921. this.scaling = BABYLON.Vector3.One();
  53922. /**
  53923. * The uvs of the particle.
  53924. */
  53925. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53926. /**
  53927. * The current speed of the particle.
  53928. */
  53929. this.velocity = BABYLON.Vector3.Zero();
  53930. /**
  53931. * The pivot point in the particle local space.
  53932. */
  53933. this.pivot = BABYLON.Vector3.Zero();
  53934. /**
  53935. * Must the particle be translated from its pivot point in its local space ?
  53936. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53937. * Default : false
  53938. */
  53939. this.translateFromPivot = false;
  53940. /**
  53941. * Is the particle active or not ?
  53942. */
  53943. this.alive = true;
  53944. /**
  53945. * Is the particle visible or not ?
  53946. */
  53947. this.isVisible = true;
  53948. /**
  53949. * Index of this particle in the global "positions" array (Internal use)
  53950. */
  53951. this._pos = 0;
  53952. /**
  53953. * Index of this particle in the global "indices" array (Internal use)
  53954. */
  53955. this._ind = 0;
  53956. /**
  53957. * ModelShape id of this particle
  53958. */
  53959. this.shapeId = 0;
  53960. /**
  53961. * Index of the particle in its shape id (Internal use)
  53962. */
  53963. this.idxInShape = 0;
  53964. /**
  53965. * Still set as invisible in order to skip useless computations (Internal use)
  53966. */
  53967. this._stillInvisible = false;
  53968. /**
  53969. * Last computed particle rotation matrix
  53970. */
  53971. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53972. /**
  53973. * Parent particle Id, if any.
  53974. * Default null.
  53975. */
  53976. this.parentId = null;
  53977. /**
  53978. * Internal global position in the SPS.
  53979. */
  53980. this._globalPosition = BABYLON.Vector3.Zero();
  53981. this.idx = particleIndex;
  53982. this._pos = positionIndex;
  53983. this._ind = indiceIndex;
  53984. this._model = model;
  53985. this.shapeId = shapeId;
  53986. this.idxInShape = idxInShape;
  53987. this._sps = sps;
  53988. if (modelBoundingInfo) {
  53989. this._modelBoundingInfo = modelBoundingInfo;
  53990. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53991. }
  53992. }
  53993. Object.defineProperty(SolidParticle.prototype, "scale", {
  53994. /**
  53995. * Legacy support, changed scale to scaling
  53996. */
  53997. get: function () {
  53998. return this.scaling;
  53999. },
  54000. /**
  54001. * Legacy support, changed scale to scaling
  54002. */
  54003. set: function (scale) {
  54004. this.scaling = scale;
  54005. },
  54006. enumerable: true,
  54007. configurable: true
  54008. });
  54009. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  54010. /**
  54011. * Legacy support, changed quaternion to rotationQuaternion
  54012. */
  54013. get: function () {
  54014. return this.rotationQuaternion;
  54015. },
  54016. /**
  54017. * Legacy support, changed quaternion to rotationQuaternion
  54018. */
  54019. set: function (q) {
  54020. this.rotationQuaternion = q;
  54021. },
  54022. enumerable: true,
  54023. configurable: true
  54024. });
  54025. /**
  54026. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  54027. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  54028. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  54029. * @returns true if it intersects
  54030. */
  54031. SolidParticle.prototype.intersectsMesh = function (target) {
  54032. if (!this._boundingInfo || !target._boundingInfo) {
  54033. return false;
  54034. }
  54035. if (this._sps._bSphereOnly) {
  54036. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  54037. }
  54038. return this._boundingInfo.intersects(target._boundingInfo, false);
  54039. };
  54040. return SolidParticle;
  54041. }());
  54042. BABYLON.SolidParticle = SolidParticle;
  54043. /**
  54044. * Represents the shape of the model used by one particle of a solid particle system.
  54045. * SPS internal tool, don't use it manually.
  54046. * @see SolidParticleSystem
  54047. */
  54048. var ModelShape = /** @class */ (function () {
  54049. /**
  54050. * 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.
  54051. * SPS internal tool, don't use it manually.
  54052. * @ignore
  54053. */
  54054. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  54055. /**
  54056. * length of the shape in the model indices array (internal use)
  54057. */
  54058. this._indicesLength = 0;
  54059. this.shapeID = id;
  54060. this._shape = shape;
  54061. this._indicesLength = indicesLength;
  54062. this._shapeUV = shapeUV;
  54063. this._positionFunction = posFunction;
  54064. this._vertexFunction = vtxFunction;
  54065. }
  54066. return ModelShape;
  54067. }());
  54068. BABYLON.ModelShape = ModelShape;
  54069. /**
  54070. * Represents a Depth Sorted Particle in the solid particle system.
  54071. * @see SolidParticleSystem
  54072. */
  54073. var DepthSortedParticle = /** @class */ (function () {
  54074. function DepthSortedParticle() {
  54075. /**
  54076. * Index of the particle in the "indices" array
  54077. */
  54078. this.ind = 0;
  54079. /**
  54080. * Length of the particle shape in the "indices" array
  54081. */
  54082. this.indicesLength = 0;
  54083. /**
  54084. * Squared distance from the particle to the camera
  54085. */
  54086. this.sqDistance = 0.0;
  54087. }
  54088. return DepthSortedParticle;
  54089. }());
  54090. BABYLON.DepthSortedParticle = DepthSortedParticle;
  54091. })(BABYLON || (BABYLON = {}));
  54092. //# sourceMappingURL=babylon.solidParticle.js.map
  54093. "use strict";
  54094. var BABYLON;
  54095. (function (BABYLON) {
  54096. /**
  54097. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  54098. *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.
  54099. * The SPS is also a particle system. It provides some methods to manage the particles.
  54100. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  54101. *
  54102. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54103. */
  54104. var SolidParticleSystem = /** @class */ (function () {
  54105. /**
  54106. * Creates a SPS (Solid Particle System) object.
  54107. * @param name (String) is the SPS name, this will be the underlying mesh name.
  54108. * @param scene (Scene) is the scene in which the SPS is added.
  54109. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  54110. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  54111. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  54112. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  54113. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54114. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54115. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54116. */
  54117. function SolidParticleSystem(name, scene, options) {
  54118. /**
  54119. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54120. * Example : var p = SPS.particles[i];
  54121. */
  54122. this.particles = new Array();
  54123. /**
  54124. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54125. */
  54126. this.nbParticles = 0;
  54127. /**
  54128. * If the particles must ever face the camera (default false). Useful for planar particles.
  54129. */
  54130. this.billboard = false;
  54131. /**
  54132. * Recompute normals when adding a shape
  54133. */
  54134. this.recomputeNormals = true;
  54135. /**
  54136. * This a counter ofr your own usage. It's not set by any SPS functions.
  54137. */
  54138. this.counter = 0;
  54139. /**
  54140. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54141. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54142. */
  54143. this.vars = {};
  54144. /**
  54145. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  54146. */
  54147. this._bSphereOnly = false;
  54148. /**
  54149. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  54150. */
  54151. this._bSphereRadiusFactor = 1.0;
  54152. this._positions = new Array();
  54153. this._indices = new Array();
  54154. this._normals = new Array();
  54155. this._colors = new Array();
  54156. this._uvs = new Array();
  54157. this._index = 0; // indices index
  54158. this._updatable = true;
  54159. this._pickable = false;
  54160. this._isVisibilityBoxLocked = false;
  54161. this._alwaysVisible = false;
  54162. this._depthSort = false;
  54163. this._shapeCounter = 0;
  54164. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  54165. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54166. this._computeParticleColor = true;
  54167. this._computeParticleTexture = true;
  54168. this._computeParticleRotation = true;
  54169. this._computeParticleVertex = false;
  54170. this._computeBoundingBox = false;
  54171. this._depthSortParticles = true;
  54172. this._cam_axisZ = BABYLON.Vector3.Zero();
  54173. this._cam_axisY = BABYLON.Vector3.Zero();
  54174. this._cam_axisX = BABYLON.Vector3.Zero();
  54175. this._axisZ = BABYLON.Axis.Z;
  54176. this._camDir = BABYLON.Vector3.Zero();
  54177. this._camInvertedPosition = BABYLON.Vector3.Zero();
  54178. this._rotMatrix = new BABYLON.Matrix();
  54179. this._invertMatrix = new BABYLON.Matrix();
  54180. this._rotated = BABYLON.Vector3.Zero();
  54181. this._quaternion = new BABYLON.Quaternion();
  54182. this._vertex = BABYLON.Vector3.Zero();
  54183. this._normal = BABYLON.Vector3.Zero();
  54184. this._yaw = 0.0;
  54185. this._pitch = 0.0;
  54186. this._roll = 0.0;
  54187. this._halfroll = 0.0;
  54188. this._halfpitch = 0.0;
  54189. this._halfyaw = 0.0;
  54190. this._sinRoll = 0.0;
  54191. this._cosRoll = 0.0;
  54192. this._sinPitch = 0.0;
  54193. this._cosPitch = 0.0;
  54194. this._sinYaw = 0.0;
  54195. this._cosYaw = 0.0;
  54196. this._mustUnrotateFixedNormals = false;
  54197. this._minimum = BABYLON.Vector3.Zero();
  54198. this._maximum = BABYLON.Vector3.Zero();
  54199. this._minBbox = BABYLON.Vector3.Zero();
  54200. this._maxBbox = BABYLON.Vector3.Zero();
  54201. this._particlesIntersect = false;
  54202. this._depthSortFunction = function (p1, p2) {
  54203. return (p2.sqDistance - p1.sqDistance);
  54204. };
  54205. this._needs32Bits = false;
  54206. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  54207. this._scaledPivot = BABYLON.Vector3.Zero();
  54208. this._particleHasParent = false;
  54209. this.name = name;
  54210. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54211. this._camera = scene.activeCamera;
  54212. this._pickable = options ? options.isPickable : false;
  54213. this._depthSort = options ? options.enableDepthSort : false;
  54214. this._particlesIntersect = options ? options.particleIntersection : false;
  54215. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54216. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54217. if (options && options.updatable) {
  54218. this._updatable = options.updatable;
  54219. }
  54220. else {
  54221. this._updatable = true;
  54222. }
  54223. if (this._pickable) {
  54224. this.pickedParticles = [];
  54225. }
  54226. if (this._depthSort) {
  54227. this.depthSortedParticles = [];
  54228. }
  54229. }
  54230. /**
  54231. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54232. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54233. * @returns the created mesh
  54234. */
  54235. SolidParticleSystem.prototype.buildMesh = function () {
  54236. if (this.nbParticles === 0) {
  54237. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54238. this.addShape(triangle, 1);
  54239. triangle.dispose();
  54240. }
  54241. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54242. this._positions32 = new Float32Array(this._positions);
  54243. this._uvs32 = new Float32Array(this._uvs);
  54244. this._colors32 = new Float32Array(this._colors);
  54245. if (this.recomputeNormals) {
  54246. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54247. }
  54248. this._normals32 = new Float32Array(this._normals);
  54249. this._fixedNormal32 = new Float32Array(this._normals);
  54250. if (this._mustUnrotateFixedNormals) {
  54251. this._unrotateFixedNormals();
  54252. }
  54253. var vertexData = new BABYLON.VertexData();
  54254. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54255. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54256. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54257. if (this._uvs32) {
  54258. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54259. ;
  54260. }
  54261. if (this._colors32) {
  54262. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54263. }
  54264. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54265. vertexData.applyToMesh(mesh, this._updatable);
  54266. this.mesh = mesh;
  54267. this.mesh.isPickable = this._pickable;
  54268. // free memory
  54269. if (!this._depthSort) {
  54270. this._indices = null;
  54271. }
  54272. this._positions = null;
  54273. this._normals = null;
  54274. this._uvs = null;
  54275. this._colors = null;
  54276. if (!this._updatable) {
  54277. this.particles.length = 0;
  54278. }
  54279. return mesh;
  54280. };
  54281. /**
  54282. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54283. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54284. * Thus the particles generated from `digest()` have their property `position` set yet.
  54285. * @param mesh ( Mesh ) is the mesh to be digested
  54286. * @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
  54287. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54288. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54289. * @returns the current SPS
  54290. */
  54291. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54292. var size = (options && options.facetNb) || 1;
  54293. var number = (options && options.number) || 0;
  54294. var delta = (options && options.delta) || 0;
  54295. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54296. var meshInd = mesh.getIndices();
  54297. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54298. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54299. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54300. var f = 0; // facet counter
  54301. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54302. // compute size from number
  54303. if (number) {
  54304. number = (number > totalFacets) ? totalFacets : number;
  54305. size = Math.round(totalFacets / number);
  54306. delta = 0;
  54307. }
  54308. else {
  54309. size = (size > totalFacets) ? totalFacets : size;
  54310. }
  54311. var facetPos = []; // submesh positions
  54312. var facetInd = []; // submesh indices
  54313. var facetUV = []; // submesh UV
  54314. var facetCol = []; // submesh colors
  54315. var barycenter = BABYLON.Vector3.Zero();
  54316. var sizeO = size;
  54317. while (f < totalFacets) {
  54318. size = sizeO + Math.floor((1 + delta) * Math.random());
  54319. if (f > totalFacets - size) {
  54320. size = totalFacets - f;
  54321. }
  54322. // reset temp arrays
  54323. facetPos.length = 0;
  54324. facetInd.length = 0;
  54325. facetUV.length = 0;
  54326. facetCol.length = 0;
  54327. // iterate over "size" facets
  54328. var fi = 0;
  54329. for (var j = f * 3; j < (f + size) * 3; j++) {
  54330. facetInd.push(fi);
  54331. var i = meshInd[j];
  54332. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54333. if (meshUV) {
  54334. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54335. }
  54336. if (meshCol) {
  54337. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54338. }
  54339. fi++;
  54340. }
  54341. // create a model shape for each single particle
  54342. var idx = this.nbParticles;
  54343. var shape = this._posToShape(facetPos);
  54344. var shapeUV = this._uvsToShapeUV(facetUV);
  54345. // compute the barycenter of the shape
  54346. var v;
  54347. for (v = 0; v < shape.length; v++) {
  54348. barycenter.addInPlace(shape[v]);
  54349. }
  54350. barycenter.scaleInPlace(1 / shape.length);
  54351. // shift the shape from its barycenter to the origin
  54352. for (v = 0; v < shape.length; v++) {
  54353. shape[v].subtractInPlace(barycenter);
  54354. }
  54355. var bInfo;
  54356. if (this._particlesIntersect) {
  54357. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54358. }
  54359. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54360. // add the particle in the SPS
  54361. var currentPos = this._positions.length;
  54362. var currentInd = this._indices.length;
  54363. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54364. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54365. // initialize the particle position
  54366. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54367. this._index += shape.length;
  54368. idx++;
  54369. this.nbParticles++;
  54370. this._shapeCounter++;
  54371. f += size;
  54372. }
  54373. return this;
  54374. };
  54375. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54376. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54377. var index = 0;
  54378. var idx = 0;
  54379. for (var p = 0; p < this.particles.length; p++) {
  54380. this._particle = this.particles[p];
  54381. this._shape = this._particle._model._shape;
  54382. if (this._particle.rotationQuaternion) {
  54383. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54384. }
  54385. else {
  54386. this._yaw = this._particle.rotation.y;
  54387. this._pitch = this._particle.rotation.x;
  54388. this._roll = this._particle.rotation.z;
  54389. this._quaternionRotationYPR();
  54390. }
  54391. this._quaternionToRotationMatrix();
  54392. this._rotMatrix.invertToRef(this._invertMatrix);
  54393. for (var pt = 0; pt < this._shape.length; pt++) {
  54394. idx = index + pt * 3;
  54395. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54396. this._fixedNormal32[idx] = this._normal.x;
  54397. this._fixedNormal32[idx + 1] = this._normal.y;
  54398. this._fixedNormal32[idx + 2] = this._normal.z;
  54399. }
  54400. index = idx + 3;
  54401. }
  54402. };
  54403. //reset copy
  54404. SolidParticleSystem.prototype._resetCopy = function () {
  54405. this._copy.position.x = 0;
  54406. this._copy.position.y = 0;
  54407. this._copy.position.z = 0;
  54408. this._copy.rotation.x = 0;
  54409. this._copy.rotation.y = 0;
  54410. this._copy.rotation.z = 0;
  54411. this._copy.rotationQuaternion = null;
  54412. this._copy.scaling.x = 1.0;
  54413. this._copy.scaling.y = 1.0;
  54414. this._copy.scaling.z = 1.0;
  54415. this._copy.uvs.x = 0;
  54416. this._copy.uvs.y = 0;
  54417. this._copy.uvs.z = 1.0;
  54418. this._copy.uvs.w = 1.0;
  54419. this._copy.color = null;
  54420. this._copy.translateFromPivot = false;
  54421. };
  54422. // _meshBuilder : inserts the shape model in the global SPS mesh
  54423. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54424. var i;
  54425. var u = 0;
  54426. var c = 0;
  54427. var n = 0;
  54428. this._resetCopy();
  54429. if (options && options.positionFunction) {
  54430. options.positionFunction(this._copy, idx, idxInShape);
  54431. this._mustUnrotateFixedNormals = true;
  54432. }
  54433. if (this._copy.rotationQuaternion) {
  54434. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54435. }
  54436. else {
  54437. this._yaw = this._copy.rotation.y;
  54438. this._pitch = this._copy.rotation.x;
  54439. this._roll = this._copy.rotation.z;
  54440. this._quaternionRotationYPR();
  54441. }
  54442. this._quaternionToRotationMatrix();
  54443. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54444. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54445. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54446. if (this._copy.translateFromPivot) {
  54447. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54448. }
  54449. else {
  54450. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54451. }
  54452. for (i = 0; i < shape.length; i++) {
  54453. this._vertex.x = shape[i].x;
  54454. this._vertex.y = shape[i].y;
  54455. this._vertex.z = shape[i].z;
  54456. if (options && options.vertexFunction) {
  54457. options.vertexFunction(this._copy, this._vertex, i);
  54458. }
  54459. this._vertex.x *= this._copy.scaling.x;
  54460. this._vertex.y *= this._copy.scaling.y;
  54461. this._vertex.z *= this._copy.scaling.z;
  54462. this._vertex.x -= this._scaledPivot.x;
  54463. this._vertex.y -= this._scaledPivot.y;
  54464. this._vertex.z -= this._scaledPivot.z;
  54465. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54466. this._rotated.addInPlace(this._pivotBackTranslation);
  54467. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54468. if (meshUV) {
  54469. 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);
  54470. u += 2;
  54471. }
  54472. if (this._copy.color) {
  54473. this._color = this._copy.color;
  54474. }
  54475. else if (meshCol && meshCol[c] !== undefined) {
  54476. this._color.r = meshCol[c];
  54477. this._color.g = meshCol[c + 1];
  54478. this._color.b = meshCol[c + 2];
  54479. this._color.a = meshCol[c + 3];
  54480. }
  54481. else {
  54482. this._color.r = 1.0;
  54483. this._color.g = 1.0;
  54484. this._color.b = 1.0;
  54485. this._color.a = 1.0;
  54486. }
  54487. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54488. c += 4;
  54489. if (!this.recomputeNormals && meshNor) {
  54490. this._normal.x = meshNor[n];
  54491. this._normal.y = meshNor[n + 1];
  54492. this._normal.z = meshNor[n + 2];
  54493. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54494. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54495. n += 3;
  54496. }
  54497. }
  54498. for (i = 0; i < meshInd.length; i++) {
  54499. var current_ind = p + meshInd[i];
  54500. indices.push(current_ind);
  54501. if (current_ind > 65535) {
  54502. this._needs32Bits = true;
  54503. }
  54504. }
  54505. if (this._pickable) {
  54506. var nbfaces = meshInd.length / 3;
  54507. for (i = 0; i < nbfaces; i++) {
  54508. this.pickedParticles.push({ idx: idx, faceId: i });
  54509. }
  54510. }
  54511. if (this._depthSort) {
  54512. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54513. }
  54514. return this._copy;
  54515. };
  54516. // returns a shape array from positions array
  54517. SolidParticleSystem.prototype._posToShape = function (positions) {
  54518. var shape = [];
  54519. for (var i = 0; i < positions.length; i += 3) {
  54520. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54521. }
  54522. return shape;
  54523. };
  54524. // returns a shapeUV array from a Vector4 uvs
  54525. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54526. var shapeUV = [];
  54527. if (uvs) {
  54528. for (var i = 0; i < uvs.length; i++)
  54529. shapeUV.push(uvs[i]);
  54530. }
  54531. return shapeUV;
  54532. };
  54533. // adds a new particle object in the particles array
  54534. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54535. if (bInfo === void 0) { bInfo = null; }
  54536. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54537. this.particles.push(sp);
  54538. return sp;
  54539. };
  54540. /**
  54541. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54542. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54543. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54544. * @param nb (positive integer) the number of particles to be created from this model
  54545. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54546. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54547. * @returns the number of shapes in the system
  54548. */
  54549. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54550. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54551. var meshInd = mesh.getIndices();
  54552. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54553. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54554. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54555. var bbInfo;
  54556. if (this._particlesIntersect) {
  54557. bbInfo = mesh.getBoundingInfo();
  54558. }
  54559. var shape = this._posToShape(meshPos);
  54560. var shapeUV = this._uvsToShapeUV(meshUV);
  54561. var posfunc = options ? options.positionFunction : null;
  54562. var vtxfunc = options ? options.vertexFunction : null;
  54563. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54564. // particles
  54565. var sp;
  54566. var currentCopy;
  54567. var idx = this.nbParticles;
  54568. for (var i = 0; i < nb; i++) {
  54569. var currentPos = this._positions.length;
  54570. var currentInd = this._indices.length;
  54571. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54572. if (this._updatable) {
  54573. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54574. sp.position.copyFrom(currentCopy.position);
  54575. sp.rotation.copyFrom(currentCopy.rotation);
  54576. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54577. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54578. }
  54579. if (currentCopy.color && sp.color) {
  54580. sp.color.copyFrom(currentCopy.color);
  54581. }
  54582. sp.scaling.copyFrom(currentCopy.scaling);
  54583. sp.uvs.copyFrom(currentCopy.uvs);
  54584. }
  54585. this._index += shape.length;
  54586. idx++;
  54587. }
  54588. this.nbParticles += nb;
  54589. this._shapeCounter++;
  54590. return this._shapeCounter - 1;
  54591. };
  54592. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54593. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54594. this._resetCopy();
  54595. if (particle._model._positionFunction) {
  54596. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54597. }
  54598. if (this._copy.rotationQuaternion) {
  54599. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54600. }
  54601. else {
  54602. this._yaw = this._copy.rotation.y;
  54603. this._pitch = this._copy.rotation.x;
  54604. this._roll = this._copy.rotation.z;
  54605. this._quaternionRotationYPR();
  54606. }
  54607. this._quaternionToRotationMatrix();
  54608. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54609. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54610. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54611. if (this._copy.translateFromPivot) {
  54612. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54613. }
  54614. else {
  54615. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54616. }
  54617. this._shape = particle._model._shape;
  54618. for (var pt = 0; pt < this._shape.length; pt++) {
  54619. this._vertex.x = this._shape[pt].x;
  54620. this._vertex.y = this._shape[pt].y;
  54621. this._vertex.z = this._shape[pt].z;
  54622. if (particle._model._vertexFunction) {
  54623. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54624. }
  54625. this._vertex.x *= this._copy.scaling.x;
  54626. this._vertex.y *= this._copy.scaling.y;
  54627. this._vertex.z *= this._copy.scaling.z;
  54628. this._vertex.x -= this._scaledPivot.x;
  54629. this._vertex.y -= this._scaledPivot.y;
  54630. this._vertex.z -= this._scaledPivot.z;
  54631. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54632. this._rotated.addInPlace(this._pivotBackTranslation);
  54633. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54634. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54635. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54636. }
  54637. particle.position.x = 0.0;
  54638. particle.position.y = 0.0;
  54639. particle.position.z = 0.0;
  54640. particle.rotation.x = 0.0;
  54641. particle.rotation.y = 0.0;
  54642. particle.rotation.z = 0.0;
  54643. particle.rotationQuaternion = null;
  54644. particle.scaling.x = 1.0;
  54645. particle.scaling.y = 1.0;
  54646. particle.scaling.z = 1.0;
  54647. particle.uvs.x = 0.0;
  54648. particle.uvs.y = 0.0;
  54649. particle.uvs.z = 1.0;
  54650. particle.uvs.w = 1.0;
  54651. particle.pivot.x = 0.0;
  54652. particle.pivot.y = 0.0;
  54653. particle.pivot.z = 0.0;
  54654. particle.translateFromPivot = false;
  54655. particle.parentId = null;
  54656. };
  54657. /**
  54658. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54659. * @returns the SPS.
  54660. */
  54661. SolidParticleSystem.prototype.rebuildMesh = function () {
  54662. for (var p = 0; p < this.particles.length; p++) {
  54663. this._rebuildParticle(this.particles[p]);
  54664. }
  54665. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54666. return this;
  54667. };
  54668. /**
  54669. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54670. * This method calls `updateParticle()` for each particle of the SPS.
  54671. * For an animated SPS, it is usually called within the render loop.
  54672. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54673. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54674. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54675. * @returns the SPS.
  54676. */
  54677. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54678. if (start === void 0) { start = 0; }
  54679. if (end === void 0) { end = this.nbParticles - 1; }
  54680. if (update === void 0) { update = true; }
  54681. if (!this._updatable) {
  54682. return this;
  54683. }
  54684. // custom beforeUpdate
  54685. this.beforeUpdateParticles(start, end, update);
  54686. this._cam_axisX.x = 1.0;
  54687. this._cam_axisX.y = 0.0;
  54688. this._cam_axisX.z = 0.0;
  54689. this._cam_axisY.x = 0.0;
  54690. this._cam_axisY.y = 1.0;
  54691. this._cam_axisY.z = 0.0;
  54692. this._cam_axisZ.x = 0.0;
  54693. this._cam_axisZ.y = 0.0;
  54694. this._cam_axisZ.z = 1.0;
  54695. // cases when the World Matrix is to be computed first
  54696. if (this.billboard || this._depthSort) {
  54697. this.mesh.computeWorldMatrix(true);
  54698. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54699. }
  54700. // if the particles will always face the camera
  54701. if (this.billboard) {
  54702. // compute the camera position and un-rotate it by the current mesh rotation
  54703. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54704. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54705. this._cam_axisZ.normalize();
  54706. // same for camera up vector extracted from the cam view matrix
  54707. var view = this._camera.getViewMatrix(true);
  54708. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54709. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54710. this._cam_axisY.normalize();
  54711. this._cam_axisX.normalize();
  54712. }
  54713. // if depthSort, compute the camera global position in the mesh local system
  54714. if (this._depthSort) {
  54715. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54716. }
  54717. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54718. var idx = 0; // current position index in the global array positions32
  54719. var index = 0; // position start index in the global array positions32 of the current particle
  54720. var colidx = 0; // current color index in the global array colors32
  54721. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54722. var uvidx = 0; // current uv index in the global array uvs32
  54723. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54724. var pt = 0; // current index in the particle model shape
  54725. if (this.mesh.isFacetDataEnabled) {
  54726. this._computeBoundingBox = true;
  54727. }
  54728. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54729. if (this._computeBoundingBox) {
  54730. if (start == 0 && end == this.nbParticles - 1) {
  54731. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54732. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54733. }
  54734. else {
  54735. if (this.mesh._boundingInfo) {
  54736. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54737. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54738. }
  54739. }
  54740. }
  54741. // particle loop
  54742. index = this.particles[start]._pos;
  54743. var vpos = (index / 3) | 0;
  54744. colorIndex = vpos * 4;
  54745. uvIndex = vpos * 2;
  54746. for (var p = start; p <= end; p++) {
  54747. this._particle = this.particles[p];
  54748. this._shape = this._particle._model._shape;
  54749. this._shapeUV = this._particle._model._shapeUV;
  54750. // call to custom user function to update the particle properties
  54751. this.updateParticle(this._particle);
  54752. // camera-particle distance for depth sorting
  54753. if (this._depthSort && this._depthSortParticles) {
  54754. var dsp = this.depthSortedParticles[p];
  54755. dsp.ind = this._particle._ind;
  54756. dsp.indicesLength = this._particle._model._indicesLength;
  54757. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54758. }
  54759. // skip the computations for inactive or already invisible particles
  54760. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54761. // increment indexes for the next particle
  54762. pt = this._shape.length;
  54763. index += pt * 3;
  54764. colorIndex += pt * 4;
  54765. uvIndex += pt * 2;
  54766. continue;
  54767. }
  54768. if (this._particle.isVisible) {
  54769. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54770. this._particleHasParent = (this._particle.parentId !== null);
  54771. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54772. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54773. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54774. // particle rotation matrix
  54775. if (this.billboard) {
  54776. this._particle.rotation.x = 0.0;
  54777. this._particle.rotation.y = 0.0;
  54778. }
  54779. if (this._computeParticleRotation || this.billboard) {
  54780. if (this._particle.rotationQuaternion) {
  54781. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54782. }
  54783. else {
  54784. this._yaw = this._particle.rotation.y;
  54785. this._pitch = this._particle.rotation.x;
  54786. this._roll = this._particle.rotation.z;
  54787. this._quaternionRotationYPR();
  54788. }
  54789. this._quaternionToRotationMatrix();
  54790. }
  54791. if (this._particleHasParent) {
  54792. this._parent = this.particles[this._particle.parentId];
  54793. 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];
  54794. 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];
  54795. 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];
  54796. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54797. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54798. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54799. if (this._computeParticleRotation || this.billboard) {
  54800. 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];
  54801. 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];
  54802. 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];
  54803. 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];
  54804. 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];
  54805. 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];
  54806. 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];
  54807. 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];
  54808. 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];
  54809. }
  54810. }
  54811. else {
  54812. this._particle._globalPosition.x = this._particle.position.x;
  54813. this._particle._globalPosition.y = this._particle.position.y;
  54814. this._particle._globalPosition.z = this._particle.position.z;
  54815. if (this._computeParticleRotation || this.billboard) {
  54816. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54817. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54818. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54819. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54820. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54821. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54822. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54823. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54824. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54825. }
  54826. }
  54827. if (this._particle.translateFromPivot) {
  54828. this._pivotBackTranslation.x = 0.0;
  54829. this._pivotBackTranslation.y = 0.0;
  54830. this._pivotBackTranslation.z = 0.0;
  54831. }
  54832. else {
  54833. this._pivotBackTranslation.x = this._scaledPivot.x;
  54834. this._pivotBackTranslation.y = this._scaledPivot.y;
  54835. this._pivotBackTranslation.z = this._scaledPivot.z;
  54836. }
  54837. // particle vertex loop
  54838. for (pt = 0; pt < this._shape.length; pt++) {
  54839. idx = index + pt * 3;
  54840. colidx = colorIndex + pt * 4;
  54841. uvidx = uvIndex + pt * 2;
  54842. this._vertex.x = this._shape[pt].x;
  54843. this._vertex.y = this._shape[pt].y;
  54844. this._vertex.z = this._shape[pt].z;
  54845. if (this._computeParticleVertex) {
  54846. this.updateParticleVertex(this._particle, this._vertex, pt);
  54847. }
  54848. // positions
  54849. this._vertex.x *= this._particle.scaling.x;
  54850. this._vertex.y *= this._particle.scaling.y;
  54851. this._vertex.z *= this._particle.scaling.z;
  54852. this._vertex.x -= this._scaledPivot.x;
  54853. this._vertex.y -= this._scaledPivot.y;
  54854. this._vertex.z -= this._scaledPivot.z;
  54855. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54856. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54857. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54858. this._rotated.x += this._pivotBackTranslation.x;
  54859. this._rotated.y += this._pivotBackTranslation.y;
  54860. this._rotated.z += this._pivotBackTranslation.z;
  54861. 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;
  54862. 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;
  54863. 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;
  54864. if (this._computeBoundingBox) {
  54865. if (this._positions32[idx] < this._minimum.x) {
  54866. this._minimum.x = this._positions32[idx];
  54867. }
  54868. if (this._positions32[idx] > this._maximum.x) {
  54869. this._maximum.x = this._positions32[idx];
  54870. }
  54871. if (this._positions32[idx + 1] < this._minimum.y) {
  54872. this._minimum.y = this._positions32[idx + 1];
  54873. }
  54874. if (this._positions32[idx + 1] > this._maximum.y) {
  54875. this._maximum.y = this._positions32[idx + 1];
  54876. }
  54877. if (this._positions32[idx + 2] < this._minimum.z) {
  54878. this._minimum.z = this._positions32[idx + 2];
  54879. }
  54880. if (this._positions32[idx + 2] > this._maximum.z) {
  54881. this._maximum.z = this._positions32[idx + 2];
  54882. }
  54883. }
  54884. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54885. if (!this._computeParticleVertex) {
  54886. this._normal.x = this._fixedNormal32[idx];
  54887. this._normal.y = this._fixedNormal32[idx + 1];
  54888. this._normal.z = this._fixedNormal32[idx + 2];
  54889. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54890. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54891. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54892. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54893. 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;
  54894. 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;
  54895. }
  54896. if (this._computeParticleColor && this._particle.color) {
  54897. this._colors32[colidx] = this._particle.color.r;
  54898. this._colors32[colidx + 1] = this._particle.color.g;
  54899. this._colors32[colidx + 2] = this._particle.color.b;
  54900. this._colors32[colidx + 3] = this._particle.color.a;
  54901. }
  54902. if (this._computeParticleTexture) {
  54903. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54904. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54905. }
  54906. }
  54907. }
  54908. else {
  54909. this._particle._stillInvisible = true; // mark the particle as invisible
  54910. for (pt = 0; pt < this._shape.length; pt++) {
  54911. idx = index + pt * 3;
  54912. colidx = colorIndex + pt * 4;
  54913. uvidx = uvIndex + pt * 2;
  54914. this._positions32[idx] = 0.0;
  54915. this._positions32[idx + 1] = 0.0;
  54916. this._positions32[idx + 2] = 0.0;
  54917. this._normals32[idx] = 0.0;
  54918. this._normals32[idx + 1] = 0.0;
  54919. this._normals32[idx + 2] = 0.0;
  54920. if (this._computeParticleColor && this._particle.color) {
  54921. this._colors32[colidx] = this._particle.color.r;
  54922. this._colors32[colidx + 1] = this._particle.color.g;
  54923. this._colors32[colidx + 2] = this._particle.color.b;
  54924. this._colors32[colidx + 3] = this._particle.color.a;
  54925. }
  54926. if (this._computeParticleTexture) {
  54927. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54928. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54929. }
  54930. }
  54931. }
  54932. // if the particle intersections must be computed : update the bbInfo
  54933. if (this._particlesIntersect) {
  54934. var bInfo = this._particle._boundingInfo;
  54935. var bBox = bInfo.boundingBox;
  54936. var bSphere = bInfo.boundingSphere;
  54937. if (!this._bSphereOnly) {
  54938. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54939. for (var b = 0; b < bBox.vectors.length; b++) {
  54940. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54941. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54942. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54943. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54944. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54945. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54946. 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;
  54947. 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;
  54948. 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;
  54949. }
  54950. bBox._update(this.mesh._worldMatrix);
  54951. }
  54952. // place and scale the particle bouding sphere in the SPS local system, then update it
  54953. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54954. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54955. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54956. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54957. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54958. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54959. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54960. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54961. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54962. 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));
  54963. bSphere._update(this.mesh._worldMatrix);
  54964. }
  54965. // increment indexes for the next particle
  54966. index = idx + 3;
  54967. colorIndex = colidx + 4;
  54968. uvIndex = uvidx + 2;
  54969. }
  54970. // if the VBO must be updated
  54971. if (update) {
  54972. if (this._computeParticleColor) {
  54973. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54974. }
  54975. if (this._computeParticleTexture) {
  54976. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54977. }
  54978. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54979. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54980. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54981. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54982. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54983. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54984. for (var i = 0; i < this._normals32.length; i++) {
  54985. this._fixedNormal32[i] = this._normals32[i];
  54986. }
  54987. }
  54988. if (!this.mesh.areNormalsFrozen) {
  54989. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54990. }
  54991. }
  54992. if (this._depthSort && this._depthSortParticles) {
  54993. this.depthSortedParticles.sort(this._depthSortFunction);
  54994. var dspl = this.depthSortedParticles.length;
  54995. var sorted = 0;
  54996. var lind = 0;
  54997. var sind = 0;
  54998. var sid = 0;
  54999. for (sorted = 0; sorted < dspl; sorted++) {
  55000. lind = this.depthSortedParticles[sorted].indicesLength;
  55001. sind = this.depthSortedParticles[sorted].ind;
  55002. for (var i = 0; i < lind; i++) {
  55003. this._indices32[sid] = this._indices[sind + i];
  55004. sid++;
  55005. }
  55006. }
  55007. this.mesh.updateIndices(this._indices32);
  55008. }
  55009. }
  55010. if (this._computeBoundingBox) {
  55011. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55012. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55013. }
  55014. this.afterUpdateParticles(start, end, update);
  55015. return this;
  55016. };
  55017. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55018. this._halfroll = this._roll * 0.5;
  55019. this._halfpitch = this._pitch * 0.5;
  55020. this._halfyaw = this._yaw * 0.5;
  55021. this._sinRoll = Math.sin(this._halfroll);
  55022. this._cosRoll = Math.cos(this._halfroll);
  55023. this._sinPitch = Math.sin(this._halfpitch);
  55024. this._cosPitch = Math.cos(this._halfpitch);
  55025. this._sinYaw = Math.sin(this._halfyaw);
  55026. this._cosYaw = Math.cos(this._halfyaw);
  55027. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  55028. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  55029. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  55030. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  55031. };
  55032. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55033. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55034. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55035. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55036. this._rotMatrix.m[3] = 0;
  55037. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55038. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55039. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55040. this._rotMatrix.m[7] = 0;
  55041. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55042. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55043. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55044. this._rotMatrix.m[11] = 0;
  55045. this._rotMatrix.m[12] = 0;
  55046. this._rotMatrix.m[13] = 0;
  55047. this._rotMatrix.m[14] = 0;
  55048. this._rotMatrix.m[15] = 1.0;
  55049. };
  55050. /**
  55051. * Disposes the SPS.
  55052. */
  55053. SolidParticleSystem.prototype.dispose = function () {
  55054. this.mesh.dispose();
  55055. this.vars = null;
  55056. // drop references to internal big arrays for the GC
  55057. this._positions = null;
  55058. this._indices = null;
  55059. this._normals = null;
  55060. this._uvs = null;
  55061. this._colors = null;
  55062. this._indices32 = null;
  55063. this._positions32 = null;
  55064. this._normals32 = null;
  55065. this._fixedNormal32 = null;
  55066. this._uvs32 = null;
  55067. this._colors32 = null;
  55068. this.pickedParticles = null;
  55069. };
  55070. /**
  55071. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55072. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55073. * @returns the SPS.
  55074. */
  55075. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55076. if (!this._isVisibilityBoxLocked) {
  55077. this.mesh.refreshBoundingInfo();
  55078. }
  55079. return this;
  55080. };
  55081. /**
  55082. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55083. * @param size the size (float) of the visibility box
  55084. * note : this doesn't lock the SPS mesh bounding box.
  55085. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55086. */
  55087. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55088. var vis = size / 2;
  55089. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55090. };
  55091. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55092. /**
  55093. * Gets whether the SPS as always visible or not
  55094. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55095. */
  55096. get: function () {
  55097. return this._alwaysVisible;
  55098. },
  55099. /**
  55100. * Sets the SPS as always visible or not
  55101. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55102. */
  55103. set: function (val) {
  55104. this._alwaysVisible = val;
  55105. this.mesh.alwaysSelectAsActiveMesh = val;
  55106. },
  55107. enumerable: true,
  55108. configurable: true
  55109. });
  55110. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55111. /**
  55112. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55113. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55114. */
  55115. get: function () {
  55116. return this._isVisibilityBoxLocked;
  55117. },
  55118. /**
  55119. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55120. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55121. */
  55122. set: function (val) {
  55123. this._isVisibilityBoxLocked = val;
  55124. var boundingInfo = this.mesh.getBoundingInfo();
  55125. boundingInfo.isLocked = val;
  55126. },
  55127. enumerable: true,
  55128. configurable: true
  55129. });
  55130. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55131. /**
  55132. * Gets if `setParticles()` computes the particle rotations or not.
  55133. * Default value : true. The SPS is faster when it's set to false.
  55134. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55135. */
  55136. get: function () {
  55137. return this._computeParticleRotation;
  55138. },
  55139. /**
  55140. * Tells to `setParticles()` to compute the particle rotations or not.
  55141. * Default value : true. The SPS is faster when it's set to false.
  55142. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55143. */
  55144. set: function (val) {
  55145. this._computeParticleRotation = val;
  55146. },
  55147. enumerable: true,
  55148. configurable: true
  55149. });
  55150. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55151. /**
  55152. * Gets if `setParticles()` computes the particle colors or not.
  55153. * Default value : true. The SPS is faster when it's set to false.
  55154. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55155. */
  55156. get: function () {
  55157. return this._computeParticleColor;
  55158. },
  55159. /**
  55160. * Tells to `setParticles()` to compute the particle colors or not.
  55161. * Default value : true. The SPS is faster when it's set to false.
  55162. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55163. */
  55164. set: function (val) {
  55165. this._computeParticleColor = val;
  55166. },
  55167. enumerable: true,
  55168. configurable: true
  55169. });
  55170. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55171. /**
  55172. * Gets if `setParticles()` computes the particle textures or not.
  55173. * Default value : true. The SPS is faster when it's set to false.
  55174. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55175. */
  55176. get: function () {
  55177. return this._computeParticleTexture;
  55178. },
  55179. set: function (val) {
  55180. this._computeParticleTexture = val;
  55181. },
  55182. enumerable: true,
  55183. configurable: true
  55184. });
  55185. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55186. /**
  55187. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  55188. * Default value : false. The SPS is faster when it's set to false.
  55189. * Note : the particle custom vertex positions aren't stored values.
  55190. */
  55191. get: function () {
  55192. return this._computeParticleVertex;
  55193. },
  55194. /**
  55195. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55196. * Default value : false. The SPS is faster when it's set to false.
  55197. * Note : the particle custom vertex positions aren't stored values.
  55198. */
  55199. set: function (val) {
  55200. this._computeParticleVertex = val;
  55201. },
  55202. enumerable: true,
  55203. configurable: true
  55204. });
  55205. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55206. /**
  55207. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  55208. */
  55209. get: function () {
  55210. return this._computeBoundingBox;
  55211. },
  55212. /**
  55213. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55214. */
  55215. set: function (val) {
  55216. this._computeBoundingBox = val;
  55217. },
  55218. enumerable: true,
  55219. configurable: true
  55220. });
  55221. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55222. /**
  55223. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55224. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55225. * Default : `true`
  55226. */
  55227. get: function () {
  55228. return this._depthSortParticles;
  55229. },
  55230. /**
  55231. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55232. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55233. * Default : `true`
  55234. */
  55235. set: function (val) {
  55236. this._depthSortParticles = val;
  55237. },
  55238. enumerable: true,
  55239. configurable: true
  55240. });
  55241. // =======================================================================
  55242. // Particle behavior logic
  55243. // these following methods may be overwritten by the user to fit his needs
  55244. /**
  55245. * This function does nothing. It may be overwritten to set all the particle first values.
  55246. * The SPS doesn't call this function, you may have to call it by your own.
  55247. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55248. */
  55249. SolidParticleSystem.prototype.initParticles = function () {
  55250. };
  55251. /**
  55252. * This function does nothing. It may be overwritten to recycle a particle.
  55253. * The SPS doesn't call this function, you may have to call it by your own.
  55254. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55255. * @param particle The particle to recycle
  55256. * @returns the recycled particle
  55257. */
  55258. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55259. return particle;
  55260. };
  55261. /**
  55262. * Updates a particle : this function should be overwritten by the user.
  55263. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55264. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55265. * @example : just set a particle position or velocity and recycle conditions
  55266. * @param particle The particle to update
  55267. * @returns the updated particle
  55268. */
  55269. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55270. return particle;
  55271. };
  55272. /**
  55273. * Updates a vertex of a particle : it can be overwritten by the user.
  55274. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55275. * @param particle the current particle
  55276. * @param vertex the current index of the current particle
  55277. * @param pt the index of the current vertex in the particle shape
  55278. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55279. * @example : just set a vertex particle position
  55280. * @returns the updated vertex
  55281. */
  55282. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55283. return vertex;
  55284. };
  55285. /**
  55286. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55287. * This does nothing and may be overwritten by the user.
  55288. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55289. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55290. * @param update the boolean update value actually passed to setParticles()
  55291. */
  55292. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55293. };
  55294. /**
  55295. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55296. * This will be passed three parameters.
  55297. * This does nothing and may be overwritten by the user.
  55298. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55299. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55300. * @param update the boolean update value actually passed to setParticles()
  55301. */
  55302. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55303. };
  55304. return SolidParticleSystem;
  55305. }());
  55306. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55307. })(BABYLON || (BABYLON = {}));
  55308. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55309. "use strict";
  55310. var BABYLON;
  55311. (function (BABYLON) {
  55312. var ShaderMaterial = /** @class */ (function (_super) {
  55313. __extends(ShaderMaterial, _super);
  55314. function ShaderMaterial(name, scene, shaderPath, options) {
  55315. var _this = _super.call(this, name, scene) || this;
  55316. _this._textures = {};
  55317. _this._textureArrays = {};
  55318. _this._floats = {};
  55319. _this._ints = {};
  55320. _this._floatsArrays = {};
  55321. _this._colors3 = {};
  55322. _this._colors3Arrays = {};
  55323. _this._colors4 = {};
  55324. _this._vectors2 = {};
  55325. _this._vectors3 = {};
  55326. _this._vectors4 = {};
  55327. _this._matrices = {};
  55328. _this._matrices3x3 = {};
  55329. _this._matrices2x2 = {};
  55330. _this._vectors2Arrays = {};
  55331. _this._vectors3Arrays = {};
  55332. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55333. _this._shaderPath = shaderPath;
  55334. options.needAlphaBlending = options.needAlphaBlending || false;
  55335. options.needAlphaTesting = options.needAlphaTesting || false;
  55336. options.attributes = options.attributes || ["position", "normal", "uv"];
  55337. options.uniforms = options.uniforms || ["worldViewProjection"];
  55338. options.uniformBuffers = options.uniformBuffers || [];
  55339. options.samplers = options.samplers || [];
  55340. options.defines = options.defines || [];
  55341. _this._options = options;
  55342. return _this;
  55343. }
  55344. ShaderMaterial.prototype.getClassName = function () {
  55345. return "ShaderMaterial";
  55346. };
  55347. ShaderMaterial.prototype.needAlphaBlending = function () {
  55348. return this._options.needAlphaBlending;
  55349. };
  55350. ShaderMaterial.prototype.needAlphaTesting = function () {
  55351. return this._options.needAlphaTesting;
  55352. };
  55353. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55354. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55355. this._options.uniforms.push(uniformName);
  55356. }
  55357. };
  55358. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55359. if (this._options.samplers.indexOf(name) === -1) {
  55360. this._options.samplers.push(name);
  55361. }
  55362. this._textures[name] = texture;
  55363. return this;
  55364. };
  55365. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55366. if (this._options.samplers.indexOf(name) === -1) {
  55367. this._options.samplers.push(name);
  55368. }
  55369. this._checkUniform(name);
  55370. this._textureArrays[name] = textures;
  55371. return this;
  55372. };
  55373. ShaderMaterial.prototype.setFloat = function (name, value) {
  55374. this._checkUniform(name);
  55375. this._floats[name] = value;
  55376. return this;
  55377. };
  55378. ShaderMaterial.prototype.setInt = function (name, value) {
  55379. this._checkUniform(name);
  55380. this._ints[name] = value;
  55381. return this;
  55382. };
  55383. ShaderMaterial.prototype.setFloats = function (name, value) {
  55384. this._checkUniform(name);
  55385. this._floatsArrays[name] = value;
  55386. return this;
  55387. };
  55388. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55389. this._checkUniform(name);
  55390. this._colors3[name] = value;
  55391. return this;
  55392. };
  55393. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55394. this._checkUniform(name);
  55395. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55396. color.toArray(arr, arr.length);
  55397. return arr;
  55398. }, []);
  55399. return this;
  55400. };
  55401. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55402. this._checkUniform(name);
  55403. this._colors4[name] = value;
  55404. return this;
  55405. };
  55406. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55407. this._checkUniform(name);
  55408. this._vectors2[name] = value;
  55409. return this;
  55410. };
  55411. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55412. this._checkUniform(name);
  55413. this._vectors3[name] = value;
  55414. return this;
  55415. };
  55416. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55417. this._checkUniform(name);
  55418. this._vectors4[name] = value;
  55419. return this;
  55420. };
  55421. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55422. this._checkUniform(name);
  55423. this._matrices[name] = value;
  55424. return this;
  55425. };
  55426. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55427. this._checkUniform(name);
  55428. this._matrices3x3[name] = value;
  55429. return this;
  55430. };
  55431. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55432. this._checkUniform(name);
  55433. this._matrices2x2[name] = value;
  55434. return this;
  55435. };
  55436. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55437. this._checkUniform(name);
  55438. this._vectors2Arrays[name] = value;
  55439. return this;
  55440. };
  55441. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55442. this._checkUniform(name);
  55443. this._vectors3Arrays[name] = value;
  55444. return this;
  55445. };
  55446. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55447. if (!mesh) {
  55448. return true;
  55449. }
  55450. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55451. return false;
  55452. }
  55453. return false;
  55454. };
  55455. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55456. var scene = this.getScene();
  55457. var engine = scene.getEngine();
  55458. if (!this.checkReadyOnEveryCall) {
  55459. if (this._renderId === scene.getRenderId()) {
  55460. if (this._checkCache(scene, mesh, useInstances)) {
  55461. return true;
  55462. }
  55463. }
  55464. }
  55465. // Instances
  55466. var defines = [];
  55467. var attribs = [];
  55468. var fallbacks = new BABYLON.EffectFallbacks();
  55469. if (useInstances) {
  55470. defines.push("#define INSTANCES");
  55471. }
  55472. for (var index = 0; index < this._options.defines.length; index++) {
  55473. defines.push(this._options.defines[index]);
  55474. }
  55475. for (var index = 0; index < this._options.attributes.length; index++) {
  55476. attribs.push(this._options.attributes[index]);
  55477. }
  55478. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55479. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55480. defines.push("#define VERTEXCOLOR");
  55481. }
  55482. // Bones
  55483. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55484. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55485. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55486. if (mesh.numBoneInfluencers > 4) {
  55487. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55488. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55489. }
  55490. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55491. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55492. fallbacks.addCPUSkinningFallback(0, mesh);
  55493. if (this._options.uniforms.indexOf("mBones") === -1) {
  55494. this._options.uniforms.push("mBones");
  55495. }
  55496. }
  55497. else {
  55498. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55499. }
  55500. // Textures
  55501. for (var name in this._textures) {
  55502. if (!this._textures[name].isReady()) {
  55503. return false;
  55504. }
  55505. }
  55506. // Alpha test
  55507. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55508. defines.push("#define ALPHATEST");
  55509. }
  55510. var previousEffect = this._effect;
  55511. var join = defines.join("\n");
  55512. this._effect = engine.createEffect(this._shaderPath, {
  55513. attributes: attribs,
  55514. uniformsNames: this._options.uniforms,
  55515. uniformBuffersNames: this._options.uniformBuffers,
  55516. samplers: this._options.samplers,
  55517. defines: join,
  55518. fallbacks: fallbacks,
  55519. onCompiled: this.onCompiled,
  55520. onError: this.onError
  55521. }, engine);
  55522. if (!this._effect.isReady()) {
  55523. return false;
  55524. }
  55525. if (previousEffect !== this._effect) {
  55526. scene.resetCachedMaterial();
  55527. }
  55528. this._renderId = scene.getRenderId();
  55529. return true;
  55530. };
  55531. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55532. var scene = this.getScene();
  55533. if (!this._effect) {
  55534. return;
  55535. }
  55536. if (this._options.uniforms.indexOf("world") !== -1) {
  55537. this._effect.setMatrix("world", world);
  55538. }
  55539. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55540. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55541. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55542. }
  55543. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55544. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55545. }
  55546. };
  55547. ShaderMaterial.prototype.bind = function (world, mesh) {
  55548. // Std values
  55549. this.bindOnlyWorldMatrix(world);
  55550. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55551. if (this._options.uniforms.indexOf("view") !== -1) {
  55552. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55553. }
  55554. if (this._options.uniforms.indexOf("projection") !== -1) {
  55555. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55556. }
  55557. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55558. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55559. }
  55560. // Bones
  55561. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55562. var name;
  55563. // Texture
  55564. for (name in this._textures) {
  55565. this._effect.setTexture(name, this._textures[name]);
  55566. }
  55567. // Texture arrays
  55568. for (name in this._textureArrays) {
  55569. this._effect.setTextureArray(name, this._textureArrays[name]);
  55570. }
  55571. // Int
  55572. for (name in this._ints) {
  55573. this._effect.setInt(name, this._ints[name]);
  55574. }
  55575. // Float
  55576. for (name in this._floats) {
  55577. this._effect.setFloat(name, this._floats[name]);
  55578. }
  55579. // Floats
  55580. for (name in this._floatsArrays) {
  55581. this._effect.setArray(name, this._floatsArrays[name]);
  55582. }
  55583. // Color3
  55584. for (name in this._colors3) {
  55585. this._effect.setColor3(name, this._colors3[name]);
  55586. }
  55587. for (name in this._colors3Arrays) {
  55588. this._effect.setArray3(name, this._colors3Arrays[name]);
  55589. }
  55590. // Color4
  55591. for (name in this._colors4) {
  55592. var color = this._colors4[name];
  55593. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55594. }
  55595. // Vector2
  55596. for (name in this._vectors2) {
  55597. this._effect.setVector2(name, this._vectors2[name]);
  55598. }
  55599. // Vector3
  55600. for (name in this._vectors3) {
  55601. this._effect.setVector3(name, this._vectors3[name]);
  55602. }
  55603. // Vector4
  55604. for (name in this._vectors4) {
  55605. this._effect.setVector4(name, this._vectors4[name]);
  55606. }
  55607. // Matrix
  55608. for (name in this._matrices) {
  55609. this._effect.setMatrix(name, this._matrices[name]);
  55610. }
  55611. // Matrix 3x3
  55612. for (name in this._matrices3x3) {
  55613. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55614. }
  55615. // Matrix 2x2
  55616. for (name in this._matrices2x2) {
  55617. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55618. }
  55619. // Vector2Array
  55620. for (name in this._vectors2Arrays) {
  55621. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55622. }
  55623. // Vector3Array
  55624. for (name in this._vectors3Arrays) {
  55625. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55626. }
  55627. }
  55628. this._afterBind(mesh);
  55629. };
  55630. ShaderMaterial.prototype.getActiveTextures = function () {
  55631. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55632. for (var name in this._textures) {
  55633. activeTextures.push(this._textures[name]);
  55634. }
  55635. for (var name in this._textureArrays) {
  55636. var array = this._textureArrays[name];
  55637. for (var index = 0; index < array.length; index++) {
  55638. activeTextures.push(array[index]);
  55639. }
  55640. }
  55641. return activeTextures;
  55642. };
  55643. ShaderMaterial.prototype.hasTexture = function (texture) {
  55644. if (_super.prototype.hasTexture.call(this, texture)) {
  55645. return true;
  55646. }
  55647. for (var name in this._textures) {
  55648. if (this._textures[name] === texture) {
  55649. return true;
  55650. }
  55651. }
  55652. for (var name in this._textureArrays) {
  55653. var array = this._textureArrays[name];
  55654. for (var index = 0; index < array.length; index++) {
  55655. if (array[index] === texture) {
  55656. return true;
  55657. }
  55658. }
  55659. }
  55660. return false;
  55661. };
  55662. ShaderMaterial.prototype.clone = function (name) {
  55663. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55664. return newShaderMaterial;
  55665. };
  55666. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55667. if (forceDisposeTextures) {
  55668. var name;
  55669. for (name in this._textures) {
  55670. this._textures[name].dispose();
  55671. }
  55672. for (name in this._textureArrays) {
  55673. var array = this._textureArrays[name];
  55674. for (var index = 0; index < array.length; index++) {
  55675. array[index].dispose();
  55676. }
  55677. }
  55678. }
  55679. this._textures = {};
  55680. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55681. };
  55682. ShaderMaterial.prototype.serialize = function () {
  55683. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55684. serializationObject.customType = "BABYLON.ShaderMaterial";
  55685. serializationObject.options = this._options;
  55686. serializationObject.shaderPath = this._shaderPath;
  55687. var name;
  55688. // Texture
  55689. serializationObject.textures = {};
  55690. for (name in this._textures) {
  55691. serializationObject.textures[name] = this._textures[name].serialize();
  55692. }
  55693. // Texture arrays
  55694. serializationObject.textureArrays = {};
  55695. for (name in this._textureArrays) {
  55696. serializationObject.textureArrays[name] = [];
  55697. var array = this._textureArrays[name];
  55698. for (var index = 0; index < array.length; index++) {
  55699. serializationObject.textureArrays[name].push(array[index].serialize());
  55700. }
  55701. }
  55702. // Float
  55703. serializationObject.floats = {};
  55704. for (name in this._floats) {
  55705. serializationObject.floats[name] = this._floats[name];
  55706. }
  55707. // Float s
  55708. serializationObject.FloatArrays = {};
  55709. for (name in this._floatsArrays) {
  55710. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55711. }
  55712. // Color3
  55713. serializationObject.colors3 = {};
  55714. for (name in this._colors3) {
  55715. serializationObject.colors3[name] = this._colors3[name].asArray();
  55716. }
  55717. // Color3 array
  55718. serializationObject.colors3Arrays = {};
  55719. for (name in this._colors3Arrays) {
  55720. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55721. }
  55722. // Color4
  55723. serializationObject.colors4 = {};
  55724. for (name in this._colors4) {
  55725. serializationObject.colors4[name] = this._colors4[name].asArray();
  55726. }
  55727. // Vector2
  55728. serializationObject.vectors2 = {};
  55729. for (name in this._vectors2) {
  55730. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55731. }
  55732. // Vector3
  55733. serializationObject.vectors3 = {};
  55734. for (name in this._vectors3) {
  55735. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55736. }
  55737. // Vector4
  55738. serializationObject.vectors4 = {};
  55739. for (name in this._vectors4) {
  55740. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55741. }
  55742. // Matrix
  55743. serializationObject.matrices = {};
  55744. for (name in this._matrices) {
  55745. serializationObject.matrices[name] = this._matrices[name].asArray();
  55746. }
  55747. // Matrix 3x3
  55748. serializationObject.matrices3x3 = {};
  55749. for (name in this._matrices3x3) {
  55750. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55751. }
  55752. // Matrix 2x2
  55753. serializationObject.matrices2x2 = {};
  55754. for (name in this._matrices2x2) {
  55755. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55756. }
  55757. // Vector2Array
  55758. serializationObject.vectors2Arrays = {};
  55759. for (name in this._vectors2Arrays) {
  55760. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55761. }
  55762. // Vector3Array
  55763. serializationObject.vectors3Arrays = {};
  55764. for (name in this._vectors3Arrays) {
  55765. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55766. }
  55767. return serializationObject;
  55768. };
  55769. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55770. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55771. var name;
  55772. // Texture
  55773. for (name in source.textures) {
  55774. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55775. }
  55776. // Texture arrays
  55777. for (name in source.textureArrays) {
  55778. var array = source.textureArrays[name];
  55779. var textureArray = new Array();
  55780. for (var index = 0; index < array.length; index++) {
  55781. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55782. }
  55783. material.setTextureArray(name, textureArray);
  55784. }
  55785. // Float
  55786. for (name in source.floats) {
  55787. material.setFloat(name, source.floats[name]);
  55788. }
  55789. // Float s
  55790. for (name in source.floatsArrays) {
  55791. material.setFloats(name, source.floatsArrays[name]);
  55792. }
  55793. // Color3
  55794. for (name in source.colors3) {
  55795. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55796. }
  55797. // Color3 arrays
  55798. for (name in source.colors3Arrays) {
  55799. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55800. if (i % 3 === 0) {
  55801. arr.push([num]);
  55802. }
  55803. else {
  55804. arr[arr.length - 1].push(num);
  55805. }
  55806. return arr;
  55807. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55808. material.setColor3Array(name, colors);
  55809. }
  55810. // Color4
  55811. for (name in source.colors4) {
  55812. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55813. }
  55814. // Vector2
  55815. for (name in source.vectors2) {
  55816. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55817. }
  55818. // Vector3
  55819. for (name in source.vectors3) {
  55820. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55821. }
  55822. // Vector4
  55823. for (name in source.vectors4) {
  55824. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55825. }
  55826. // Matrix
  55827. for (name in source.matrices) {
  55828. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55829. }
  55830. // Matrix 3x3
  55831. for (name in source.matrices3x3) {
  55832. material.setMatrix3x3(name, source.matrices3x3[name]);
  55833. }
  55834. // Matrix 2x2
  55835. for (name in source.matrices2x2) {
  55836. material.setMatrix2x2(name, source.matrices2x2[name]);
  55837. }
  55838. // Vector2Array
  55839. for (name in source.vectors2Arrays) {
  55840. material.setArray2(name, source.vectors2Arrays[name]);
  55841. }
  55842. // Vector3Array
  55843. for (name in source.vectors3Arrays) {
  55844. material.setArray3(name, source.vectors3Arrays[name]);
  55845. }
  55846. return material;
  55847. };
  55848. return ShaderMaterial;
  55849. }(BABYLON.Material));
  55850. BABYLON.ShaderMaterial = ShaderMaterial;
  55851. })(BABYLON || (BABYLON = {}));
  55852. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55853. "use strict";
  55854. var BABYLON;
  55855. (function (BABYLON) {
  55856. var GroundMesh = /** @class */ (function (_super) {
  55857. __extends(GroundMesh, _super);
  55858. function GroundMesh(name, scene) {
  55859. var _this = _super.call(this, name, scene) || this;
  55860. _this.generateOctree = false;
  55861. return _this;
  55862. }
  55863. GroundMesh.prototype.getClassName = function () {
  55864. return "GroundMesh";
  55865. };
  55866. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55867. get: function () {
  55868. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55869. },
  55870. enumerable: true,
  55871. configurable: true
  55872. });
  55873. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55874. get: function () {
  55875. return this._subdivisionsX;
  55876. },
  55877. enumerable: true,
  55878. configurable: true
  55879. });
  55880. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55881. get: function () {
  55882. return this._subdivisionsY;
  55883. },
  55884. enumerable: true,
  55885. configurable: true
  55886. });
  55887. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55888. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55889. this._subdivisionsX = chunksCount;
  55890. this._subdivisionsY = chunksCount;
  55891. this.subdivide(chunksCount);
  55892. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55893. };
  55894. /**
  55895. * Returns a height (y) value in the Worl system :
  55896. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55897. * Returns the ground y position if (x, z) are outside the ground surface.
  55898. */
  55899. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55900. var world = this.getWorldMatrix();
  55901. var invMat = BABYLON.Tmp.Matrix[5];
  55902. world.invertToRef(invMat);
  55903. var tmpVect = BABYLON.Tmp.Vector3[8];
  55904. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55905. x = tmpVect.x;
  55906. z = tmpVect.z;
  55907. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55908. return this.position.y;
  55909. }
  55910. if (!this._heightQuads || this._heightQuads.length == 0) {
  55911. this._initHeightQuads();
  55912. this._computeHeightQuads();
  55913. }
  55914. var facet = this._getFacetAt(x, z);
  55915. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55916. // return y in the World system
  55917. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55918. return tmpVect.y;
  55919. };
  55920. /**
  55921. * Returns a normalized vector (Vector3) orthogonal to the ground
  55922. * at the ground coordinates (x, z) expressed in the World system.
  55923. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55924. */
  55925. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55926. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55927. this.getNormalAtCoordinatesToRef(x, z, normal);
  55928. return normal;
  55929. };
  55930. /**
  55931. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55932. * at the ground coordinates (x, z) expressed in the World system.
  55933. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55934. * Returns the GroundMesh.
  55935. */
  55936. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55937. var world = this.getWorldMatrix();
  55938. var tmpMat = BABYLON.Tmp.Matrix[5];
  55939. world.invertToRef(tmpMat);
  55940. var tmpVect = BABYLON.Tmp.Vector3[8];
  55941. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55942. x = tmpVect.x;
  55943. z = tmpVect.z;
  55944. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55945. return this;
  55946. }
  55947. if (!this._heightQuads || this._heightQuads.length == 0) {
  55948. this._initHeightQuads();
  55949. this._computeHeightQuads();
  55950. }
  55951. var facet = this._getFacetAt(x, z);
  55952. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55953. return this;
  55954. };
  55955. /**
  55956. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55957. * if the ground has been updated.
  55958. * This can be used in the render loop.
  55959. * Returns the GroundMesh.
  55960. */
  55961. GroundMesh.prototype.updateCoordinateHeights = function () {
  55962. if (!this._heightQuads || this._heightQuads.length == 0) {
  55963. this._initHeightQuads();
  55964. }
  55965. this._computeHeightQuads();
  55966. return this;
  55967. };
  55968. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55969. GroundMesh.prototype._getFacetAt = function (x, z) {
  55970. // retrieve col and row from x, z coordinates in the ground local system
  55971. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55972. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55973. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55974. var facet;
  55975. if (z < quad.slope.x * x + quad.slope.y) {
  55976. facet = quad.facet1;
  55977. }
  55978. else {
  55979. facet = quad.facet2;
  55980. }
  55981. return facet;
  55982. };
  55983. // Creates and populates the heightMap array with "facet" elements :
  55984. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55985. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55986. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55987. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55988. // Returns the GroundMesh.
  55989. GroundMesh.prototype._initHeightQuads = function () {
  55990. var subdivisionsX = this._subdivisionsX;
  55991. var subdivisionsY = this._subdivisionsY;
  55992. this._heightQuads = new Array();
  55993. for (var row = 0; row < subdivisionsY; row++) {
  55994. for (var col = 0; col < subdivisionsX; col++) {
  55995. 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) };
  55996. this._heightQuads[row * subdivisionsX + col] = quad;
  55997. }
  55998. }
  55999. return this;
  56000. };
  56001. // Compute each quad element values and update the the heightMap array :
  56002. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  56003. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  56004. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  56005. // Returns the GroundMesh.
  56006. GroundMesh.prototype._computeHeightQuads = function () {
  56007. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56008. if (!positions) {
  56009. return this;
  56010. }
  56011. var v1 = BABYLON.Tmp.Vector3[3];
  56012. var v2 = BABYLON.Tmp.Vector3[2];
  56013. var v3 = BABYLON.Tmp.Vector3[1];
  56014. var v4 = BABYLON.Tmp.Vector3[0];
  56015. var v1v2 = BABYLON.Tmp.Vector3[4];
  56016. var v1v3 = BABYLON.Tmp.Vector3[5];
  56017. var v1v4 = BABYLON.Tmp.Vector3[6];
  56018. var norm1 = BABYLON.Tmp.Vector3[7];
  56019. var norm2 = BABYLON.Tmp.Vector3[8];
  56020. var i = 0;
  56021. var j = 0;
  56022. var k = 0;
  56023. var cd = 0; // 2D slope coefficient : z = cd * x + h
  56024. var h = 0;
  56025. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  56026. var d2 = 0;
  56027. var subdivisionsX = this._subdivisionsX;
  56028. var subdivisionsY = this._subdivisionsY;
  56029. for (var row = 0; row < subdivisionsY; row++) {
  56030. for (var col = 0; col < subdivisionsX; col++) {
  56031. i = col * 3;
  56032. j = row * (subdivisionsX + 1) * 3;
  56033. k = (row + 1) * (subdivisionsX + 1) * 3;
  56034. v1.x = positions[j + i];
  56035. v1.y = positions[j + i + 1];
  56036. v1.z = positions[j + i + 2];
  56037. v2.x = positions[j + i + 3];
  56038. v2.y = positions[j + i + 4];
  56039. v2.z = positions[j + i + 5];
  56040. v3.x = positions[k + i];
  56041. v3.y = positions[k + i + 1];
  56042. v3.z = positions[k + i + 2];
  56043. v4.x = positions[k + i + 3];
  56044. v4.y = positions[k + i + 4];
  56045. v4.z = positions[k + i + 5];
  56046. // 2D slope V1V4
  56047. cd = (v4.z - v1.z) / (v4.x - v1.x);
  56048. h = v1.z - cd * v1.x; // v1 belongs to the slope
  56049. // facet equations :
  56050. // we compute each facet normal vector
  56051. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  56052. // we compute the value d by applying the equation to v1 which belongs to the plane
  56053. // then we store the facet equation in a Vector4
  56054. v2.subtractToRef(v1, v1v2);
  56055. v3.subtractToRef(v1, v1v3);
  56056. v4.subtractToRef(v1, v1v4);
  56057. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  56058. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  56059. norm1.normalize();
  56060. norm2.normalize();
  56061. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  56062. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  56063. var quad = this._heightQuads[row * subdivisionsX + col];
  56064. quad.slope.copyFromFloats(cd, h);
  56065. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  56066. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  56067. }
  56068. }
  56069. return this;
  56070. };
  56071. GroundMesh.prototype.serialize = function (serializationObject) {
  56072. _super.prototype.serialize.call(this, serializationObject);
  56073. serializationObject.subdivisionsX = this._subdivisionsX;
  56074. serializationObject.subdivisionsY = this._subdivisionsY;
  56075. serializationObject.minX = this._minX;
  56076. serializationObject.maxX = this._maxX;
  56077. serializationObject.minZ = this._minZ;
  56078. serializationObject.maxZ = this._maxZ;
  56079. serializationObject.width = this._width;
  56080. serializationObject.height = this._height;
  56081. };
  56082. GroundMesh.Parse = function (parsedMesh, scene) {
  56083. var result = new GroundMesh(parsedMesh.name, scene);
  56084. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  56085. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  56086. result._minX = parsedMesh.minX;
  56087. result._maxX = parsedMesh.maxX;
  56088. result._minZ = parsedMesh.minZ;
  56089. result._maxZ = parsedMesh.maxZ;
  56090. result._width = parsedMesh.width;
  56091. result._height = parsedMesh.height;
  56092. return result;
  56093. };
  56094. return GroundMesh;
  56095. }(BABYLON.Mesh));
  56096. BABYLON.GroundMesh = GroundMesh;
  56097. })(BABYLON || (BABYLON = {}));
  56098. //# sourceMappingURL=babylon.groundMesh.js.map
  56099. "use strict";
  56100. var BABYLON;
  56101. (function (BABYLON) {
  56102. /**
  56103. * Creates an instance based on a source mesh.
  56104. */
  56105. var InstancedMesh = /** @class */ (function (_super) {
  56106. __extends(InstancedMesh, _super);
  56107. function InstancedMesh(name, source) {
  56108. var _this = _super.call(this, name, source.getScene()) || this;
  56109. source.instances.push(_this);
  56110. _this._sourceMesh = source;
  56111. _this.position.copyFrom(source.position);
  56112. _this.rotation.copyFrom(source.rotation);
  56113. _this.scaling.copyFrom(source.scaling);
  56114. if (source.rotationQuaternion) {
  56115. _this.rotationQuaternion = source.rotationQuaternion.clone();
  56116. }
  56117. _this.infiniteDistance = source.infiniteDistance;
  56118. _this.setPivotMatrix(source.getPivotMatrix());
  56119. _this.refreshBoundingInfo();
  56120. _this._syncSubMeshes();
  56121. return _this;
  56122. }
  56123. /**
  56124. * Returns the string "InstancedMesh".
  56125. */
  56126. InstancedMesh.prototype.getClassName = function () {
  56127. return "InstancedMesh";
  56128. };
  56129. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  56130. // Methods
  56131. get: function () {
  56132. return this._sourceMesh.receiveShadows;
  56133. },
  56134. enumerable: true,
  56135. configurable: true
  56136. });
  56137. Object.defineProperty(InstancedMesh.prototype, "material", {
  56138. get: function () {
  56139. return this._sourceMesh.material;
  56140. },
  56141. enumerable: true,
  56142. configurable: true
  56143. });
  56144. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  56145. get: function () {
  56146. return this._sourceMesh.visibility;
  56147. },
  56148. enumerable: true,
  56149. configurable: true
  56150. });
  56151. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  56152. get: function () {
  56153. return this._sourceMesh.skeleton;
  56154. },
  56155. enumerable: true,
  56156. configurable: true
  56157. });
  56158. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  56159. get: function () {
  56160. return this._sourceMesh.renderingGroupId;
  56161. },
  56162. set: function (value) {
  56163. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  56164. return;
  56165. }
  56166. //no-op with warning
  56167. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  56168. },
  56169. enumerable: true,
  56170. configurable: true
  56171. });
  56172. /**
  56173. * Returns the total number of vertices (integer).
  56174. */
  56175. InstancedMesh.prototype.getTotalVertices = function () {
  56176. return this._sourceMesh.getTotalVertices();
  56177. };
  56178. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  56179. get: function () {
  56180. return this._sourceMesh;
  56181. },
  56182. enumerable: true,
  56183. configurable: true
  56184. });
  56185. /**
  56186. * Is this node ready to be used/rendered
  56187. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  56188. * @return {boolean} is it ready
  56189. */
  56190. InstancedMesh.prototype.isReady = function (completeCheck) {
  56191. if (completeCheck === void 0) { completeCheck = false; }
  56192. return this._sourceMesh.isReady(completeCheck, true);
  56193. };
  56194. /**
  56195. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  56196. */
  56197. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  56198. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  56199. };
  56200. /**
  56201. * Sets the vertex data of the mesh geometry for the requested `kind`.
  56202. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  56203. * The `data` are either a numeric array either a Float32Array.
  56204. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  56205. * 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).
  56206. * Note that a new underlying VertexBuffer object is created each call.
  56207. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  56208. *
  56209. * Possible `kind` values :
  56210. * - BABYLON.VertexBuffer.PositionKind
  56211. * - BABYLON.VertexBuffer.UVKind
  56212. * - BABYLON.VertexBuffer.UV2Kind
  56213. * - BABYLON.VertexBuffer.UV3Kind
  56214. * - BABYLON.VertexBuffer.UV4Kind
  56215. * - BABYLON.VertexBuffer.UV5Kind
  56216. * - BABYLON.VertexBuffer.UV6Kind
  56217. * - BABYLON.VertexBuffer.ColorKind
  56218. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56219. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56220. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56221. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56222. *
  56223. * Returns the Mesh.
  56224. */
  56225. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56226. if (this.sourceMesh) {
  56227. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56228. }
  56229. return this.sourceMesh;
  56230. };
  56231. /**
  56232. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56233. * If the mesh has no geometry, it is simply returned as it is.
  56234. * The `data` are either a numeric array either a Float32Array.
  56235. * No new underlying VertexBuffer object is created.
  56236. * 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.
  56237. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56238. *
  56239. * Possible `kind` values :
  56240. * - BABYLON.VertexBuffer.PositionKind
  56241. * - BABYLON.VertexBuffer.UVKind
  56242. * - BABYLON.VertexBuffer.UV2Kind
  56243. * - BABYLON.VertexBuffer.UV3Kind
  56244. * - BABYLON.VertexBuffer.UV4Kind
  56245. * - BABYLON.VertexBuffer.UV5Kind
  56246. * - BABYLON.VertexBuffer.UV6Kind
  56247. * - BABYLON.VertexBuffer.ColorKind
  56248. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56249. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56250. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56251. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56252. *
  56253. * Returns the Mesh.
  56254. */
  56255. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56256. if (this.sourceMesh) {
  56257. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56258. }
  56259. return this.sourceMesh;
  56260. };
  56261. /**
  56262. * Sets the mesh indices.
  56263. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56264. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56265. * This method creates a new index buffer each call.
  56266. * Returns the Mesh.
  56267. */
  56268. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56269. if (totalVertices === void 0) { totalVertices = null; }
  56270. if (this.sourceMesh) {
  56271. this.sourceMesh.setIndices(indices, totalVertices);
  56272. }
  56273. return this.sourceMesh;
  56274. };
  56275. /**
  56276. * Boolean : True if the mesh owns the requested kind of data.
  56277. */
  56278. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56279. return this._sourceMesh.isVerticesDataPresent(kind);
  56280. };
  56281. /**
  56282. * Returns an array of indices (IndicesArray).
  56283. */
  56284. InstancedMesh.prototype.getIndices = function () {
  56285. return this._sourceMesh.getIndices();
  56286. };
  56287. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56288. get: function () {
  56289. return this._sourceMesh._positions;
  56290. },
  56291. enumerable: true,
  56292. configurable: true
  56293. });
  56294. /**
  56295. * Sets a new updated BoundingInfo to the mesh.
  56296. * Returns the mesh.
  56297. */
  56298. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56299. var meshBB = this._sourceMesh.getBoundingInfo();
  56300. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56301. this._updateBoundingInfo();
  56302. return this;
  56303. };
  56304. InstancedMesh.prototype._preActivate = function () {
  56305. if (this._currentLOD) {
  56306. this._currentLOD._preActivate();
  56307. }
  56308. return this;
  56309. };
  56310. InstancedMesh.prototype._activate = function (renderId) {
  56311. if (this._currentLOD) {
  56312. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56313. }
  56314. return this;
  56315. };
  56316. /**
  56317. * Returns the current associated LOD AbstractMesh.
  56318. */
  56319. InstancedMesh.prototype.getLOD = function (camera) {
  56320. if (!camera) {
  56321. return this;
  56322. }
  56323. var boundingInfo = this.getBoundingInfo();
  56324. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56325. if (this._currentLOD === this.sourceMesh) {
  56326. return this;
  56327. }
  56328. return this._currentLOD;
  56329. };
  56330. InstancedMesh.prototype._syncSubMeshes = function () {
  56331. this.releaseSubMeshes();
  56332. if (this._sourceMesh.subMeshes) {
  56333. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56334. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56335. }
  56336. }
  56337. return this;
  56338. };
  56339. InstancedMesh.prototype._generatePointsArray = function () {
  56340. return this._sourceMesh._generatePointsArray();
  56341. };
  56342. /**
  56343. * Creates a new InstancedMesh from the current mesh.
  56344. * - name (string) : the cloned mesh name
  56345. * - newParent (optional Node) : the optional Node to parent the clone to.
  56346. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56347. *
  56348. * Returns the clone.
  56349. */
  56350. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56351. var result = this._sourceMesh.createInstance(name);
  56352. // Deep copy
  56353. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56354. // Bounding info
  56355. this.refreshBoundingInfo();
  56356. // Parent
  56357. if (newParent) {
  56358. result.parent = newParent;
  56359. }
  56360. if (!doNotCloneChildren) {
  56361. // Children
  56362. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56363. var mesh = this.getScene().meshes[index];
  56364. if (mesh.parent === this) {
  56365. mesh.clone(mesh.name, result);
  56366. }
  56367. }
  56368. }
  56369. result.computeWorldMatrix(true);
  56370. return result;
  56371. };
  56372. /**
  56373. * Disposes the InstancedMesh.
  56374. * Returns nothing.
  56375. */
  56376. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56377. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56378. // Remove from mesh
  56379. var index = this._sourceMesh.instances.indexOf(this);
  56380. this._sourceMesh.instances.splice(index, 1);
  56381. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56382. };
  56383. return InstancedMesh;
  56384. }(BABYLON.AbstractMesh));
  56385. BABYLON.InstancedMesh = InstancedMesh;
  56386. })(BABYLON || (BABYLON = {}));
  56387. //# sourceMappingURL=babylon.instancedMesh.js.map
  56388. "use strict";
  56389. var BABYLON;
  56390. (function (BABYLON) {
  56391. var LinesMesh = /** @class */ (function (_super) {
  56392. __extends(LinesMesh, _super);
  56393. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56394. if (scene === void 0) { scene = null; }
  56395. if (parent === void 0) { parent = null; }
  56396. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56397. _this.useVertexColor = useVertexColor;
  56398. _this.useVertexAlpha = useVertexAlpha;
  56399. _this.color = new BABYLON.Color3(1, 1, 1);
  56400. _this.alpha = 1;
  56401. if (source) {
  56402. _this.color = source.color.clone();
  56403. _this.alpha = source.alpha;
  56404. _this.useVertexColor = source.useVertexColor;
  56405. _this.useVertexAlpha = source.useVertexAlpha;
  56406. }
  56407. _this._intersectionThreshold = 0.1;
  56408. var defines = [];
  56409. var options = {
  56410. attributes: [BABYLON.VertexBuffer.PositionKind],
  56411. uniforms: ["world", "viewProjection"],
  56412. needAlphaBlending: true,
  56413. defines: defines
  56414. };
  56415. if (useVertexAlpha === false) {
  56416. options.needAlphaBlending = false;
  56417. }
  56418. if (!useVertexColor) {
  56419. options.uniforms.push("color");
  56420. }
  56421. else {
  56422. options.defines.push("#define VERTEXCOLOR");
  56423. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56424. }
  56425. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56426. return _this;
  56427. }
  56428. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56429. /**
  56430. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56431. * This margin is expressed in world space coordinates, so its value may vary.
  56432. * Default value is 0.1
  56433. * @returns the intersection Threshold value.
  56434. */
  56435. get: function () {
  56436. return this._intersectionThreshold;
  56437. },
  56438. /**
  56439. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56440. * This margin is expressed in world space coordinates, so its value may vary.
  56441. * @param value the new threshold to apply
  56442. */
  56443. set: function (value) {
  56444. if (this._intersectionThreshold === value) {
  56445. return;
  56446. }
  56447. this._intersectionThreshold = value;
  56448. if (this.geometry) {
  56449. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56450. }
  56451. },
  56452. enumerable: true,
  56453. configurable: true
  56454. });
  56455. /**
  56456. * Returns the string "LineMesh"
  56457. */
  56458. LinesMesh.prototype.getClassName = function () {
  56459. return "LinesMesh";
  56460. };
  56461. Object.defineProperty(LinesMesh.prototype, "material", {
  56462. get: function () {
  56463. return this._colorShader;
  56464. },
  56465. set: function (value) {
  56466. // Do nothing
  56467. },
  56468. enumerable: true,
  56469. configurable: true
  56470. });
  56471. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56472. get: function () {
  56473. return false;
  56474. },
  56475. enumerable: true,
  56476. configurable: true
  56477. });
  56478. LinesMesh.prototype.createInstance = function (name) {
  56479. throw new Error("LinesMeshes do not support createInstance.");
  56480. };
  56481. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56482. if (!this._geometry) {
  56483. return this;
  56484. }
  56485. // VBOs
  56486. this._geometry._bind(this._colorShader.getEffect());
  56487. // Color
  56488. if (!this.useVertexColor) {
  56489. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56490. }
  56491. return this;
  56492. };
  56493. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56494. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56495. return this;
  56496. }
  56497. var engine = this.getScene().getEngine();
  56498. // Draw order
  56499. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56500. return this;
  56501. };
  56502. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56503. this._colorShader.dispose();
  56504. _super.prototype.dispose.call(this, doNotRecurse);
  56505. };
  56506. /**
  56507. * Returns a new LineMesh object cloned from the current one.
  56508. */
  56509. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56510. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56511. };
  56512. return LinesMesh;
  56513. }(BABYLON.Mesh));
  56514. BABYLON.LinesMesh = LinesMesh;
  56515. })(BABYLON || (BABYLON = {}));
  56516. //# sourceMappingURL=babylon.linesMesh.js.map
  56517. "use strict";
  56518. var BABYLON;
  56519. (function (BABYLON) {
  56520. var MeshBuilder = /** @class */ (function () {
  56521. function MeshBuilder() {
  56522. }
  56523. MeshBuilder.updateSideOrientation = function (orientation) {
  56524. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56525. return BABYLON.Mesh.DOUBLESIDE;
  56526. }
  56527. if (orientation === undefined || orientation === null) {
  56528. return BABYLON.Mesh.FRONTSIDE;
  56529. }
  56530. return orientation;
  56531. };
  56532. /**
  56533. * Creates a box mesh.
  56534. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56535. * The parameter `size` sets the size (float) of each box side (default 1).
  56536. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56537. * 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).
  56538. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56539. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56540. * 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).
  56541. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56542. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56543. */
  56544. MeshBuilder.CreateBox = function (name, options, scene) {
  56545. if (scene === void 0) { scene = null; }
  56546. var box = new BABYLON.Mesh(name, scene);
  56547. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56548. box._originalBuilderSideOrientation = options.sideOrientation;
  56549. var vertexData = BABYLON.VertexData.CreateBox(options);
  56550. vertexData.applyToMesh(box, options.updatable);
  56551. return box;
  56552. };
  56553. /**
  56554. * Creates a sphere mesh.
  56555. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56556. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56557. * 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`).
  56558. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56559. * 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
  56560. * 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).
  56561. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56562. * 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).
  56563. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56565. */
  56566. MeshBuilder.CreateSphere = function (name, options, scene) {
  56567. var sphere = new BABYLON.Mesh(name, scene);
  56568. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56569. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56570. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56571. vertexData.applyToMesh(sphere, options.updatable);
  56572. return sphere;
  56573. };
  56574. /**
  56575. * Creates a plane polygonal mesh. By default, this is a disc.
  56576. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56577. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56578. * 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.
  56579. * 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
  56580. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56581. * 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).
  56582. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56583. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56584. */
  56585. MeshBuilder.CreateDisc = function (name, options, scene) {
  56586. if (scene === void 0) { scene = null; }
  56587. var disc = new BABYLON.Mesh(name, scene);
  56588. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56589. disc._originalBuilderSideOrientation = options.sideOrientation;
  56590. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56591. vertexData.applyToMesh(disc, options.updatable);
  56592. return disc;
  56593. };
  56594. /**
  56595. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56596. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56597. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56598. * 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`).
  56599. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56600. * 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.
  56601. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56602. * 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).
  56603. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56604. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56605. */
  56606. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56607. var sphere = new BABYLON.Mesh(name, scene);
  56608. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56609. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56610. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56611. vertexData.applyToMesh(sphere, options.updatable);
  56612. return sphere;
  56613. };
  56614. ;
  56615. /**
  56616. * Creates a ribbon mesh.
  56617. * 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.
  56618. *
  56619. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56620. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56621. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56622. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56623. * 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.
  56624. * 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.
  56625. * 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
  56626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56627. * 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).
  56628. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56629. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56630. * 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.
  56631. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56632. * 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
  56633. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56634. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56635. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56636. */
  56637. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56638. if (scene === void 0) { scene = null; }
  56639. var pathArray = options.pathArray;
  56640. var closeArray = options.closeArray;
  56641. var closePath = options.closePath;
  56642. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56643. var instance = options.instance;
  56644. var updatable = options.updatable;
  56645. if (instance) {
  56646. // positionFunction : ribbon case
  56647. // only pathArray and sideOrientation parameters are taken into account for positions update
  56648. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56649. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56650. var positionFunction = function (positions) {
  56651. var minlg = pathArray[0].length;
  56652. var i = 0;
  56653. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56654. for (var si = 1; si <= ns; si++) {
  56655. for (var p = 0; p < pathArray.length; p++) {
  56656. var path = pathArray[p];
  56657. var l = path.length;
  56658. minlg = (minlg < l) ? minlg : l;
  56659. var j = 0;
  56660. while (j < minlg) {
  56661. positions[i] = path[j].x;
  56662. positions[i + 1] = path[j].y;
  56663. positions[i + 2] = path[j].z;
  56664. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56665. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56666. }
  56667. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56668. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56669. }
  56670. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56671. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56672. }
  56673. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56674. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56675. }
  56676. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56677. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56678. }
  56679. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56680. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56681. }
  56682. j++;
  56683. i += 3;
  56684. }
  56685. if (instance._closePath) {
  56686. positions[i] = path[0].x;
  56687. positions[i + 1] = path[0].y;
  56688. positions[i + 2] = path[0].z;
  56689. i += 3;
  56690. }
  56691. }
  56692. }
  56693. };
  56694. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56695. positionFunction(positions);
  56696. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56697. instance._boundingInfo.update(instance._worldMatrix);
  56698. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56699. if (options.colors) {
  56700. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56701. for (var c = 0; c < options.colors.length; c++) {
  56702. colors[c * 4] = options.colors[c].r;
  56703. colors[c * 4 + 1] = options.colors[c].g;
  56704. colors[c * 4 + 2] = options.colors[c].b;
  56705. colors[c * 4 + 3] = options.colors[c].a;
  56706. }
  56707. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56708. }
  56709. if (options.uvs) {
  56710. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56711. for (var i = 0; i < options.uvs.length; i++) {
  56712. uvs[i * 2] = options.uvs[i].x;
  56713. uvs[i * 2 + 1] = options.uvs[i].y;
  56714. }
  56715. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56716. }
  56717. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56718. var indices = instance.getIndices();
  56719. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56720. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56721. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56722. if (instance._closePath) {
  56723. var indexFirst = 0;
  56724. var indexLast = 0;
  56725. for (var p = 0; p < pathArray.length; p++) {
  56726. indexFirst = instance._idx[p] * 3;
  56727. if (p + 1 < pathArray.length) {
  56728. indexLast = (instance._idx[p + 1] - 1) * 3;
  56729. }
  56730. else {
  56731. indexLast = normals.length - 3;
  56732. }
  56733. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56734. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56735. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56736. normals[indexLast] = normals[indexFirst];
  56737. normals[indexLast + 1] = normals[indexFirst + 1];
  56738. normals[indexLast + 2] = normals[indexFirst + 2];
  56739. }
  56740. }
  56741. if (!(instance.areNormalsFrozen)) {
  56742. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56743. }
  56744. }
  56745. return instance;
  56746. }
  56747. else {
  56748. var ribbon = new BABYLON.Mesh(name, scene);
  56749. ribbon._originalBuilderSideOrientation = sideOrientation;
  56750. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56751. if (closePath) {
  56752. ribbon._idx = vertexData._idx;
  56753. }
  56754. ribbon._closePath = closePath;
  56755. ribbon._closeArray = closeArray;
  56756. vertexData.applyToMesh(ribbon, updatable);
  56757. return ribbon;
  56758. }
  56759. };
  56760. /**
  56761. * Creates a cylinder or a cone mesh.
  56762. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56763. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56764. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56765. * 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.
  56766. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56767. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56768. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56769. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56770. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56771. * 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).
  56772. * 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
  56773. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56774. * 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
  56775. * 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.
  56776. * If `enclose` is false, a ring surface is one element.
  56777. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56778. * 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
  56779. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56780. * 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).
  56781. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56783. */
  56784. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56785. var cylinder = new BABYLON.Mesh(name, scene);
  56786. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56787. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56788. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56789. vertexData.applyToMesh(cylinder, options.updatable);
  56790. return cylinder;
  56791. };
  56792. /**
  56793. * Creates a torus mesh.
  56794. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56795. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56796. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56797. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56798. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56799. * 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).
  56800. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56801. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56802. */
  56803. MeshBuilder.CreateTorus = function (name, options, scene) {
  56804. var torus = new BABYLON.Mesh(name, scene);
  56805. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56806. torus._originalBuilderSideOrientation = options.sideOrientation;
  56807. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56808. vertexData.applyToMesh(torus, options.updatable);
  56809. return torus;
  56810. };
  56811. /**
  56812. * Creates a torus knot mesh.
  56813. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56814. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56815. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56816. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56817. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56819. * 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).
  56820. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56821. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56822. */
  56823. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56824. var torusKnot = new BABYLON.Mesh(name, scene);
  56825. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56826. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56827. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56828. vertexData.applyToMesh(torusKnot, options.updatable);
  56829. return torusKnot;
  56830. };
  56831. /**
  56832. * Creates a line system mesh.
  56833. * A line system is a pool of many lines gathered in a single mesh.
  56834. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56835. * 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.
  56836. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56837. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56838. * 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
  56839. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56840. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56841. * 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
  56842. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56844. */
  56845. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56846. var instance = options.instance;
  56847. var lines = options.lines;
  56848. var colors = options.colors;
  56849. if (instance) {
  56850. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56851. var vertexColor;
  56852. var lineColors;
  56853. if (colors) {
  56854. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56855. }
  56856. var i = 0;
  56857. var c = 0;
  56858. for (var l = 0; l < lines.length; l++) {
  56859. var points = lines[l];
  56860. for (var p = 0; p < points.length; p++) {
  56861. positions[i] = points[p].x;
  56862. positions[i + 1] = points[p].y;
  56863. positions[i + 2] = points[p].z;
  56864. if (colors && vertexColor) {
  56865. lineColors = colors[l];
  56866. vertexColor[c] = lineColors[p].r;
  56867. vertexColor[c + 1] = lineColors[p].g;
  56868. vertexColor[c + 2] = lineColors[p].b;
  56869. vertexColor[c + 3] = lineColors[p].a;
  56870. c += 4;
  56871. }
  56872. i += 3;
  56873. }
  56874. }
  56875. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56876. if (colors && vertexColor) {
  56877. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56878. }
  56879. return instance;
  56880. }
  56881. // line system creation
  56882. var useVertexColor = (colors) ? true : false;
  56883. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56884. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56885. vertexData.applyToMesh(lineSystem, options.updatable);
  56886. return lineSystem;
  56887. };
  56888. /**
  56889. * Creates a line mesh.
  56890. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56891. * 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.
  56892. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56893. * The parameter `points` is an array successive Vector3.
  56894. * 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
  56895. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56896. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56897. * When updating an instance, remember that only point positions can change, not the number of points.
  56898. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56899. */
  56900. MeshBuilder.CreateLines = function (name, options, scene) {
  56901. if (scene === void 0) { scene = null; }
  56902. var colors = (options.colors) ? [options.colors] : null;
  56903. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56904. return lines;
  56905. };
  56906. /**
  56907. * Creates a dashed line mesh.
  56908. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56909. * 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.
  56910. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56911. * The parameter `points` is an array successive Vector3.
  56912. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56913. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56914. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56915. * 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
  56916. * When updating an instance, remember that only point positions can change, not the number of points.
  56917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56918. */
  56919. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56920. if (scene === void 0) { scene = null; }
  56921. var points = options.points;
  56922. var instance = options.instance;
  56923. var gapSize = options.gapSize || 1;
  56924. var dashSize = options.dashSize || 3;
  56925. if (instance) {
  56926. var positionFunction = function (positions) {
  56927. var curvect = BABYLON.Vector3.Zero();
  56928. var nbSeg = positions.length / 6;
  56929. var lg = 0;
  56930. var nb = 0;
  56931. var shft = 0;
  56932. var dashshft = 0;
  56933. var curshft = 0;
  56934. var p = 0;
  56935. var i = 0;
  56936. var j = 0;
  56937. for (i = 0; i < points.length - 1; i++) {
  56938. points[i + 1].subtractToRef(points[i], curvect);
  56939. lg += curvect.length();
  56940. }
  56941. shft = lg / nbSeg;
  56942. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56943. for (i = 0; i < points.length - 1; i++) {
  56944. points[i + 1].subtractToRef(points[i], curvect);
  56945. nb = Math.floor(curvect.length() / shft);
  56946. curvect.normalize();
  56947. j = 0;
  56948. while (j < nb && p < positions.length) {
  56949. curshft = shft * j;
  56950. positions[p] = points[i].x + curshft * curvect.x;
  56951. positions[p + 1] = points[i].y + curshft * curvect.y;
  56952. positions[p + 2] = points[i].z + curshft * curvect.z;
  56953. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56954. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56955. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56956. p += 6;
  56957. j++;
  56958. }
  56959. }
  56960. while (p < positions.length) {
  56961. positions[p] = points[i].x;
  56962. positions[p + 1] = points[i].y;
  56963. positions[p + 2] = points[i].z;
  56964. p += 3;
  56965. }
  56966. };
  56967. instance.updateMeshPositions(positionFunction, false);
  56968. return instance;
  56969. }
  56970. // dashed lines creation
  56971. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56972. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56973. vertexData.applyToMesh(dashedLines, options.updatable);
  56974. dashedLines.dashSize = dashSize;
  56975. dashedLines.gapSize = gapSize;
  56976. return dashedLines;
  56977. };
  56978. /**
  56979. * Creates an extruded shape mesh.
  56980. * 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.
  56981. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56982. *
  56983. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56984. * 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
  56985. * extruded along the Z axis.
  56986. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56987. * 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.
  56988. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56989. * 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
  56990. * 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
  56991. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56992. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56993. * 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).
  56994. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56995. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56997. */
  56998. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56999. if (scene === void 0) { scene = null; }
  57000. var path = options.path;
  57001. var shape = options.shape;
  57002. var scale = options.scale || 1;
  57003. var rotation = options.rotation || 0;
  57004. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57005. var updatable = options.updatable;
  57006. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57007. var instance = options.instance || null;
  57008. var invertUV = options.invertUV || false;
  57009. 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);
  57010. };
  57011. /**
  57012. * Creates an custom extruded shape mesh.
  57013. * 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.
  57014. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  57015. *
  57016. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  57017. * 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
  57018. * extruded along the Z axis.
  57019. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  57020. * 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
  57021. * and the distance of this point from the begining of the path :
  57022. * ```javascript
  57023. * var rotationFunction = function(i, distance) {
  57024. * // do things
  57025. * return rotationValue; }
  57026. * ```
  57027. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  57028. * 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
  57029. * and the distance of this point from the begining of the path :
  57030. * ```javascript
  57031. * var scaleFunction = function(i, distance) {
  57032. * // do things
  57033. * return scaleValue;}
  57034. * ```
  57035. * It must returns a float value that will be the scale value applied to the shape on each path point.
  57036. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  57037. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  57038. * 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
  57039. * 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
  57040. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57041. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57042. * 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).
  57043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57044. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57046. */
  57047. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  57048. var path = options.path;
  57049. var shape = options.shape;
  57050. var scaleFunction = options.scaleFunction || (function () { return 1; });
  57051. var rotationFunction = options.rotationFunction || (function () { return 0; });
  57052. var ribbonCloseArray = options.ribbonCloseArray || false;
  57053. var ribbonClosePath = options.ribbonClosePath || false;
  57054. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57055. var updatable = options.updatable;
  57056. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57057. var instance = options.instance;
  57058. var invertUV = options.invertUV || false;
  57059. 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);
  57060. };
  57061. /**
  57062. * Creates lathe mesh.
  57063. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  57064. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  57065. *
  57066. * 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
  57067. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  57068. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  57069. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  57070. * 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.
  57071. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  57072. * 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
  57073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57074. * 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).
  57075. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57076. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57077. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57078. */
  57079. MeshBuilder.CreateLathe = function (name, options, scene) {
  57080. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  57081. var closed = (options.closed === undefined) ? true : options.closed;
  57082. var shape = options.shape;
  57083. var radius = options.radius || 1;
  57084. var tessellation = options.tessellation || 64;
  57085. var updatable = options.updatable;
  57086. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57087. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57088. var pi2 = Math.PI * 2;
  57089. var paths = new Array();
  57090. var invertUV = options.invertUV || false;
  57091. var i = 0;
  57092. var p = 0;
  57093. var step = pi2 / tessellation * arc;
  57094. var rotated;
  57095. var path = new Array();
  57096. ;
  57097. for (i = 0; i <= tessellation; i++) {
  57098. var path = [];
  57099. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  57100. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  57101. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  57102. }
  57103. for (p = 0; p < shape.length; p++) {
  57104. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  57105. path.push(rotated);
  57106. }
  57107. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  57108. 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));
  57109. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  57110. }
  57111. paths.push(path);
  57112. }
  57113. // lathe ribbon
  57114. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57115. return lathe;
  57116. };
  57117. /**
  57118. * Creates a plane mesh.
  57119. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57120. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  57121. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  57122. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  57123. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57124. * 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).
  57125. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57126. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57127. */
  57128. MeshBuilder.CreatePlane = function (name, options, scene) {
  57129. var plane = new BABYLON.Mesh(name, scene);
  57130. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57131. plane._originalBuilderSideOrientation = options.sideOrientation;
  57132. var vertexData = BABYLON.VertexData.CreatePlane(options);
  57133. vertexData.applyToMesh(plane, options.updatable);
  57134. if (options.sourcePlane) {
  57135. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  57136. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  57137. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  57138. plane.rotate(vectorProduct, product);
  57139. }
  57140. return plane;
  57141. };
  57142. /**
  57143. * Creates a ground mesh.
  57144. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57145. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  57146. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  57147. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57148. */
  57149. MeshBuilder.CreateGround = function (name, options, scene) {
  57150. var ground = new BABYLON.GroundMesh(name, scene);
  57151. ground._setReady(false);
  57152. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  57153. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  57154. ground._width = options.width || 1;
  57155. ground._height = options.height || 1;
  57156. ground._maxX = ground._width / 2;
  57157. ground._maxZ = ground._height / 2;
  57158. ground._minX = -ground._maxX;
  57159. ground._minZ = -ground._maxZ;
  57160. var vertexData = BABYLON.VertexData.CreateGround(options);
  57161. vertexData.applyToMesh(ground, options.updatable);
  57162. ground._setReady(true);
  57163. return ground;
  57164. };
  57165. /**
  57166. * Creates a tiled ground mesh.
  57167. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  57168. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  57169. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  57170. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  57171. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  57172. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  57173. * numbers of subdivisions on the ground width and height of each tile.
  57174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57175. */
  57176. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  57177. var tiledGround = new BABYLON.Mesh(name, scene);
  57178. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  57179. vertexData.applyToMesh(tiledGround, options.updatable);
  57180. return tiledGround;
  57181. };
  57182. /**
  57183. * Creates a ground mesh from a height map.
  57184. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  57185. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  57186. * The parameter `url` sets the URL of the height map image resource.
  57187. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  57188. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  57189. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  57190. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  57191. * 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.
  57192. * 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).
  57193. * This function is passed the newly built mesh :
  57194. * ```javascript
  57195. * function(mesh) { // do things
  57196. * return; }
  57197. * ```
  57198. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57199. */
  57200. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  57201. var width = options.width || 10.0;
  57202. var height = options.height || 10.0;
  57203. var subdivisions = options.subdivisions || 1 | 0;
  57204. var minHeight = options.minHeight || 0.0;
  57205. var maxHeight = options.maxHeight || 1.0;
  57206. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  57207. var updatable = options.updatable;
  57208. var onReady = options.onReady;
  57209. var ground = new BABYLON.GroundMesh(name, scene);
  57210. ground._subdivisionsX = subdivisions;
  57211. ground._subdivisionsY = subdivisions;
  57212. ground._width = width;
  57213. ground._height = height;
  57214. ground._maxX = ground._width / 2.0;
  57215. ground._maxZ = ground._height / 2.0;
  57216. ground._minX = -ground._maxX;
  57217. ground._minZ = -ground._maxZ;
  57218. ground._setReady(false);
  57219. var onload = function (img) {
  57220. // Getting height map data
  57221. var canvas = document.createElement("canvas");
  57222. var context = canvas.getContext("2d");
  57223. if (!context) {
  57224. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57225. }
  57226. if (scene.isDisposed) {
  57227. return;
  57228. }
  57229. var bufferWidth = img.width;
  57230. var bufferHeight = img.height;
  57231. canvas.width = bufferWidth;
  57232. canvas.height = bufferHeight;
  57233. context.drawImage(img, 0, 0);
  57234. // Create VertexData from map data
  57235. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57236. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57237. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57238. width: width, height: height,
  57239. subdivisions: subdivisions,
  57240. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57241. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57242. });
  57243. vertexData.applyToMesh(ground, updatable);
  57244. //execute ready callback, if set
  57245. if (onReady) {
  57246. onReady(ground);
  57247. }
  57248. ground._setReady(true);
  57249. };
  57250. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57251. return ground;
  57252. };
  57253. /**
  57254. * Creates a polygon mesh.
  57255. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57256. * 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.
  57257. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57259. * 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).
  57260. * Remember you can only change the shape positions, not their number when updating a polygon.
  57261. */
  57262. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57263. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57264. var shape = options.shape;
  57265. var holes = options.holes || [];
  57266. var depth = options.depth || 0;
  57267. var contours = [];
  57268. var hole = [];
  57269. for (var i = 0; i < shape.length; i++) {
  57270. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57271. }
  57272. var epsilon = 0.00000001;
  57273. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57274. contours.pop();
  57275. }
  57276. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57277. for (var hNb = 0; hNb < holes.length; hNb++) {
  57278. hole = [];
  57279. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57280. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57281. }
  57282. polygonTriangulation.addHole(hole);
  57283. }
  57284. var polygon = polygonTriangulation.build(options.updatable, depth);
  57285. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57286. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57287. vertexData.applyToMesh(polygon, options.updatable);
  57288. return polygon;
  57289. };
  57290. ;
  57291. /**
  57292. * Creates an extruded polygon mesh, with depth in the Y direction.
  57293. * 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).
  57294. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57295. */
  57296. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57297. return MeshBuilder.CreatePolygon(name, options, scene);
  57298. };
  57299. ;
  57300. /**
  57301. * Creates a tube mesh.
  57302. * 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.
  57303. *
  57304. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57305. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57306. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57307. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57308. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57309. * 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.
  57310. * It must return a radius value (positive float) :
  57311. * ```javascript
  57312. * var radiusFunction = function(i, distance) {
  57313. * // do things
  57314. * return radius; }
  57315. * ```
  57316. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57317. * 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
  57318. * 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
  57319. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57320. * 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).
  57321. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57322. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57324. */
  57325. MeshBuilder.CreateTube = function (name, options, scene) {
  57326. var path = options.path;
  57327. var instance = options.instance;
  57328. var radius = 1.0;
  57329. if (instance) {
  57330. radius = instance.radius;
  57331. }
  57332. if (options.radius !== undefined) {
  57333. radius = options.radius;
  57334. }
  57335. ;
  57336. var tessellation = options.tessellation || 64 | 0;
  57337. var radiusFunction = options.radiusFunction || null;
  57338. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57339. var invertUV = options.invertUV || false;
  57340. var updatable = options.updatable;
  57341. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57342. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57343. // tube geometry
  57344. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57345. var tangents = path3D.getTangents();
  57346. var normals = path3D.getNormals();
  57347. var distances = path3D.getDistances();
  57348. var pi2 = Math.PI * 2;
  57349. var step = pi2 / tessellation * arc;
  57350. var returnRadius = function () { return radius; };
  57351. var radiusFunctionFinal = radiusFunction || returnRadius;
  57352. var circlePath;
  57353. var rad;
  57354. var normal;
  57355. var rotated;
  57356. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57357. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57358. for (var i = 0; i < path.length; i++) {
  57359. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57360. circlePath = Array(); // current circle array
  57361. normal = normals[i]; // current normal
  57362. for (var t = 0; t < tessellation; t++) {
  57363. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57364. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57365. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57366. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57367. circlePath[t] = rotated;
  57368. }
  57369. circlePaths[index] = circlePath;
  57370. index++;
  57371. }
  57372. // cap
  57373. var capPath = function (nbPoints, pathIndex) {
  57374. var pointCap = Array();
  57375. for (var i = 0; i < nbPoints; i++) {
  57376. pointCap.push(path[pathIndex]);
  57377. }
  57378. return pointCap;
  57379. };
  57380. switch (cap) {
  57381. case BABYLON.Mesh.NO_CAP:
  57382. break;
  57383. case BABYLON.Mesh.CAP_START:
  57384. circlePaths[0] = capPath(tessellation, 0);
  57385. circlePaths[1] = circlePaths[2].slice(0);
  57386. break;
  57387. case BABYLON.Mesh.CAP_END:
  57388. circlePaths[index] = circlePaths[index - 1].slice(0);
  57389. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57390. break;
  57391. case BABYLON.Mesh.CAP_ALL:
  57392. circlePaths[0] = capPath(tessellation, 0);
  57393. circlePaths[1] = circlePaths[2].slice(0);
  57394. circlePaths[index] = circlePaths[index - 1].slice(0);
  57395. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57396. break;
  57397. default:
  57398. break;
  57399. }
  57400. return circlePaths;
  57401. };
  57402. var path3D;
  57403. var pathArray;
  57404. if (instance) {
  57405. var arc = options.arc || instance.arc;
  57406. path3D = (instance.path3D).update(path);
  57407. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57408. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57409. instance.path3D = path3D;
  57410. instance.pathArray = pathArray;
  57411. instance.arc = arc;
  57412. instance.radius = radius;
  57413. return instance;
  57414. }
  57415. // tube creation
  57416. path3D = new BABYLON.Path3D(path);
  57417. var newPathArray = new Array();
  57418. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57419. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57420. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57421. tube.pathArray = pathArray;
  57422. tube.path3D = path3D;
  57423. tube.tessellation = tessellation;
  57424. tube.cap = cap;
  57425. tube.arc = options.arc;
  57426. tube.radius = radius;
  57427. return tube;
  57428. };
  57429. /**
  57430. * Creates a polyhedron mesh.
  57431. *
  57432. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57433. * 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
  57434. * to choose the wanted type.
  57435. * The parameter `size` (positive float, default 1) sets the polygon size.
  57436. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57437. * 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`.
  57438. * 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
  57439. * 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)`).
  57440. * 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
  57441. * 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.
  57442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57443. * 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).
  57444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57446. */
  57447. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57448. var polyhedron = new BABYLON.Mesh(name, scene);
  57449. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57450. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57451. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57452. vertexData.applyToMesh(polyhedron, options.updatable);
  57453. return polyhedron;
  57454. };
  57455. /**
  57456. * Creates a decal mesh.
  57457. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57458. * 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.
  57459. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57460. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57461. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57462. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57463. */
  57464. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57465. var indices = sourceMesh.getIndices();
  57466. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57467. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57468. var position = options.position || BABYLON.Vector3.Zero();
  57469. var normal = options.normal || BABYLON.Vector3.Up();
  57470. var size = options.size || BABYLON.Vector3.One();
  57471. var angle = options.angle || 0;
  57472. // Getting correct rotation
  57473. if (!normal) {
  57474. var target = new BABYLON.Vector3(0, 0, 1);
  57475. var camera = sourceMesh.getScene().activeCamera;
  57476. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57477. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57478. }
  57479. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57480. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57481. var pitch = Math.atan2(normal.y, len);
  57482. // Matrix
  57483. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57484. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57485. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57486. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57487. var vertexData = new BABYLON.VertexData();
  57488. vertexData.indices = [];
  57489. vertexData.positions = [];
  57490. vertexData.normals = [];
  57491. vertexData.uvs = [];
  57492. var currentVertexDataIndex = 0;
  57493. var extractDecalVector3 = function (indexId) {
  57494. var result = new BABYLON.PositionNormalVertex();
  57495. if (!indices || !positions || !normals) {
  57496. return result;
  57497. }
  57498. var vertexId = indices[indexId];
  57499. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57500. // Send vector to decal local world
  57501. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57502. // Get normal
  57503. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57504. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57505. return result;
  57506. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57507. var clip = function (vertices, axis) {
  57508. if (vertices.length === 0) {
  57509. return vertices;
  57510. }
  57511. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57512. var clipVertices = function (v0, v1) {
  57513. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57514. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57515. };
  57516. var result = new Array();
  57517. for (var index = 0; index < vertices.length; index += 3) {
  57518. var v1Out;
  57519. var v2Out;
  57520. var v3Out;
  57521. var total = 0;
  57522. var nV1 = null;
  57523. var nV2 = null;
  57524. var nV3 = null;
  57525. var nV4 = null;
  57526. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57527. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57528. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57529. v1Out = d1 > 0;
  57530. v2Out = d2 > 0;
  57531. v3Out = d3 > 0;
  57532. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57533. switch (total) {
  57534. case 0:
  57535. result.push(vertices[index]);
  57536. result.push(vertices[index + 1]);
  57537. result.push(vertices[index + 2]);
  57538. break;
  57539. case 1:
  57540. if (v1Out) {
  57541. nV1 = vertices[index + 1];
  57542. nV2 = vertices[index + 2];
  57543. nV3 = clipVertices(vertices[index], nV1);
  57544. nV4 = clipVertices(vertices[index], nV2);
  57545. }
  57546. if (v2Out) {
  57547. nV1 = vertices[index];
  57548. nV2 = vertices[index + 2];
  57549. nV3 = clipVertices(vertices[index + 1], nV1);
  57550. nV4 = clipVertices(vertices[index + 1], nV2);
  57551. result.push(nV3);
  57552. result.push(nV2.clone());
  57553. result.push(nV1.clone());
  57554. result.push(nV2.clone());
  57555. result.push(nV3.clone());
  57556. result.push(nV4);
  57557. break;
  57558. }
  57559. if (v3Out) {
  57560. nV1 = vertices[index];
  57561. nV2 = vertices[index + 1];
  57562. nV3 = clipVertices(vertices[index + 2], nV1);
  57563. nV4 = clipVertices(vertices[index + 2], nV2);
  57564. }
  57565. if (nV1 && nV2 && nV3 && nV4) {
  57566. result.push(nV1.clone());
  57567. result.push(nV2.clone());
  57568. result.push(nV3);
  57569. result.push(nV4);
  57570. result.push(nV3.clone());
  57571. result.push(nV2.clone());
  57572. }
  57573. break;
  57574. case 2:
  57575. if (!v1Out) {
  57576. nV1 = vertices[index].clone();
  57577. nV2 = clipVertices(nV1, vertices[index + 1]);
  57578. nV3 = clipVertices(nV1, vertices[index + 2]);
  57579. result.push(nV1);
  57580. result.push(nV2);
  57581. result.push(nV3);
  57582. }
  57583. if (!v2Out) {
  57584. nV1 = vertices[index + 1].clone();
  57585. nV2 = clipVertices(nV1, vertices[index + 2]);
  57586. nV3 = clipVertices(nV1, vertices[index]);
  57587. result.push(nV1);
  57588. result.push(nV2);
  57589. result.push(nV3);
  57590. }
  57591. if (!v3Out) {
  57592. nV1 = vertices[index + 2].clone();
  57593. nV2 = clipVertices(nV1, vertices[index]);
  57594. nV3 = clipVertices(nV1, vertices[index + 1]);
  57595. result.push(nV1);
  57596. result.push(nV2);
  57597. result.push(nV3);
  57598. }
  57599. break;
  57600. case 3:
  57601. break;
  57602. }
  57603. }
  57604. return result;
  57605. };
  57606. for (var index = 0; index < indices.length; index += 3) {
  57607. var faceVertices = new Array();
  57608. faceVertices.push(extractDecalVector3(index));
  57609. faceVertices.push(extractDecalVector3(index + 1));
  57610. faceVertices.push(extractDecalVector3(index + 2));
  57611. // Clip
  57612. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57613. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57614. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57615. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57616. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57617. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57618. if (faceVertices.length === 0) {
  57619. continue;
  57620. }
  57621. // Add UVs and get back to world
  57622. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57623. var vertex = faceVertices[vIndex];
  57624. //TODO check for Int32Array | Uint32Array | Uint16Array
  57625. vertexData.indices.push(currentVertexDataIndex);
  57626. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57627. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57628. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57629. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57630. currentVertexDataIndex++;
  57631. }
  57632. }
  57633. // Return mesh
  57634. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57635. vertexData.applyToMesh(decal);
  57636. decal.position = position.clone();
  57637. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57638. return decal;
  57639. };
  57640. // Privates
  57641. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57642. // extrusion geometry
  57643. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57644. var tangents = path3D.getTangents();
  57645. var normals = path3D.getNormals();
  57646. var binormals = path3D.getBinormals();
  57647. var distances = path3D.getDistances();
  57648. var angle = 0;
  57649. var returnScale = function () { return scale !== null ? scale : 1; };
  57650. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57651. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57652. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57653. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57654. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57655. for (var i = 0; i < curve.length; i++) {
  57656. var shapePath = new Array();
  57657. var angleStep = rotate(i, distances[i]);
  57658. var scaleRatio = scl(i, distances[i]);
  57659. for (var p = 0; p < shape.length; p++) {
  57660. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57661. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57662. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57663. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57664. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57665. shapePath[p] = rotated;
  57666. }
  57667. shapePaths[index] = shapePath;
  57668. angle += angleStep;
  57669. index++;
  57670. }
  57671. // cap
  57672. var capPath = function (shapePath) {
  57673. var pointCap = Array();
  57674. var barycenter = BABYLON.Vector3.Zero();
  57675. var i;
  57676. for (i = 0; i < shapePath.length; i++) {
  57677. barycenter.addInPlace(shapePath[i]);
  57678. }
  57679. barycenter.scaleInPlace(1.0 / shapePath.length);
  57680. for (i = 0; i < shapePath.length; i++) {
  57681. pointCap.push(barycenter);
  57682. }
  57683. return pointCap;
  57684. };
  57685. switch (cap) {
  57686. case BABYLON.Mesh.NO_CAP:
  57687. break;
  57688. case BABYLON.Mesh.CAP_START:
  57689. shapePaths[0] = capPath(shapePaths[2]);
  57690. shapePaths[1] = shapePaths[2];
  57691. break;
  57692. case BABYLON.Mesh.CAP_END:
  57693. shapePaths[index] = shapePaths[index - 1];
  57694. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57695. break;
  57696. case BABYLON.Mesh.CAP_ALL:
  57697. shapePaths[0] = capPath(shapePaths[2]);
  57698. shapePaths[1] = shapePaths[2];
  57699. shapePaths[index] = shapePaths[index - 1];
  57700. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57701. break;
  57702. default:
  57703. break;
  57704. }
  57705. return shapePaths;
  57706. };
  57707. var path3D;
  57708. var pathArray;
  57709. if (instance) {
  57710. path3D = (instance.path3D).update(curve);
  57711. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57712. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57713. return instance;
  57714. }
  57715. // extruded shape creation
  57716. path3D = new BABYLON.Path3D(curve);
  57717. var newShapePaths = new Array();
  57718. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57719. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57720. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57721. extrudedGeneric.pathArray = pathArray;
  57722. extrudedGeneric.path3D = path3D;
  57723. extrudedGeneric.cap = cap;
  57724. return extrudedGeneric;
  57725. };
  57726. return MeshBuilder;
  57727. }());
  57728. BABYLON.MeshBuilder = MeshBuilder;
  57729. })(BABYLON || (BABYLON = {}));
  57730. //# sourceMappingURL=babylon.meshBuilder.js.map
  57731. "use strict";
  57732. var BABYLON;
  57733. (function (BABYLON) {
  57734. /**
  57735. * Draco compression (https://google.github.io/draco/)
  57736. */
  57737. var DracoCompression = /** @class */ (function () {
  57738. /**
  57739. * Constructor
  57740. * @param numWorkers The number of workers for async operations
  57741. */
  57742. function DracoCompression(numWorkers) {
  57743. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57744. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57745. if (!workerBlobUrl || !Worker) {
  57746. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57747. return;
  57748. }
  57749. var workers = new Array(numWorkers);
  57750. for (var i = 0; i < workers.length; i++) {
  57751. var worker = new Worker(workerBlobUrl);
  57752. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57753. workers[i] = worker;
  57754. }
  57755. this._workerPool = new BABYLON.WorkerPool(workers);
  57756. }
  57757. /**
  57758. * Stop all async operations and release resources.
  57759. */
  57760. DracoCompression.prototype.dispose = function () {
  57761. this._workerPool.dispose();
  57762. delete this._workerPool;
  57763. };
  57764. /**
  57765. * Decode Draco compressed mesh data to vertex data.
  57766. * @param data The array buffer view for the Draco compression data
  57767. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57768. * @returns A promise that resolves with the decoded vertex data
  57769. */
  57770. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57771. var _this = this;
  57772. return new Promise(function (resolve, reject) {
  57773. _this._workerPool.push(function (worker, onComplete) {
  57774. var vertexData = new BABYLON.VertexData();
  57775. var onError = function (error) {
  57776. worker.removeEventListener("error", onError);
  57777. worker.removeEventListener("message", onMessage);
  57778. reject(error);
  57779. onComplete();
  57780. };
  57781. var onMessage = function (message) {
  57782. if (message.data === "done") {
  57783. worker.removeEventListener("error", onError);
  57784. worker.removeEventListener("message", onMessage);
  57785. resolve(vertexData);
  57786. onComplete();
  57787. }
  57788. else if (message.data.id === "indices") {
  57789. vertexData.indices = message.data.value;
  57790. }
  57791. else {
  57792. vertexData.set(message.data.value, message.data.id);
  57793. }
  57794. };
  57795. worker.addEventListener("error", onError);
  57796. worker.addEventListener("message", onMessage);
  57797. var dataCopy = new Uint8Array(data.byteLength);
  57798. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57799. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57800. });
  57801. });
  57802. };
  57803. /**
  57804. * The worker function that gets converted to a blob url to pass into a worker.
  57805. */
  57806. DracoCompression._Worker = function () {
  57807. // self is actually a DedicatedWorkerGlobalScope
  57808. var _self = self;
  57809. var decodeMesh = function (data, attributes) {
  57810. var dracoModule = new DracoDecoderModule();
  57811. var buffer = new dracoModule.DecoderBuffer();
  57812. buffer.Init(data, data.byteLength);
  57813. var decoder = new dracoModule.Decoder();
  57814. var geometry;
  57815. var status;
  57816. try {
  57817. var type = decoder.GetEncodedGeometryType(buffer);
  57818. switch (type) {
  57819. case dracoModule.TRIANGULAR_MESH:
  57820. geometry = new dracoModule.Mesh();
  57821. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57822. break;
  57823. case dracoModule.POINT_CLOUD:
  57824. geometry = new dracoModule.PointCloud();
  57825. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57826. break;
  57827. default:
  57828. throw new Error("Invalid geometry type " + type);
  57829. }
  57830. if (!status.ok() || !geometry.ptr) {
  57831. throw new Error(status.error_msg());
  57832. }
  57833. var numPoints = geometry.num_points();
  57834. if (type === dracoModule.TRIANGULAR_MESH) {
  57835. var numFaces = geometry.num_faces();
  57836. var faceIndices = new dracoModule.DracoInt32Array();
  57837. try {
  57838. var indices = new Uint32Array(numFaces * 3);
  57839. for (var i = 0; i < numFaces; i++) {
  57840. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57841. var offset = i * 3;
  57842. indices[offset + 0] = faceIndices.GetValue(0);
  57843. indices[offset + 1] = faceIndices.GetValue(1);
  57844. indices[offset + 2] = faceIndices.GetValue(2);
  57845. }
  57846. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57847. }
  57848. finally {
  57849. dracoModule.destroy(faceIndices);
  57850. }
  57851. }
  57852. for (var kind in attributes) {
  57853. var uniqueId = attributes[kind];
  57854. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57855. var dracoData = new dracoModule.DracoFloat32Array();
  57856. try {
  57857. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57858. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57859. for (var i = 0; i < babylonData.length; i++) {
  57860. babylonData[i] = dracoData.GetValue(i);
  57861. }
  57862. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57863. }
  57864. finally {
  57865. dracoModule.destroy(dracoData);
  57866. }
  57867. }
  57868. }
  57869. finally {
  57870. if (geometry) {
  57871. dracoModule.destroy(geometry);
  57872. }
  57873. dracoModule.destroy(decoder);
  57874. dracoModule.destroy(buffer);
  57875. }
  57876. _self.postMessage("done");
  57877. };
  57878. _self.onmessage = function (event) {
  57879. switch (event.data.id) {
  57880. case "initDecoder": {
  57881. importScripts(event.data.url);
  57882. break;
  57883. }
  57884. case "decodeMesh": {
  57885. decodeMesh(event.data.data, event.data.attributes);
  57886. break;
  57887. }
  57888. }
  57889. };
  57890. };
  57891. DracoCompression._GetDefaultDecoderUrl = function () {
  57892. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57893. return null;
  57894. }
  57895. for (var i = 0; i < document.scripts.length; i++) {
  57896. if (document.scripts[i].type === "text/x-draco-decoder") {
  57897. return document.scripts[i].src;
  57898. }
  57899. }
  57900. return null;
  57901. };
  57902. /**
  57903. * Gets the url to the draco decoder if available.
  57904. */
  57905. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57906. return DracoCompression;
  57907. }());
  57908. BABYLON.DracoCompression = DracoCompression;
  57909. })(BABYLON || (BABYLON = {}));
  57910. //# sourceMappingURL=babylon.dracoCompression.js.map
  57911. "use strict";
  57912. var BABYLON;
  57913. (function (BABYLON) {
  57914. var AudioEngine = /** @class */ (function () {
  57915. function AudioEngine() {
  57916. this._audioContext = null;
  57917. this._audioContextInitialized = false;
  57918. this.canUseWebAudio = false;
  57919. this.WarnedWebAudioUnsupported = false;
  57920. this.unlocked = false;
  57921. this.isMP3supported = false;
  57922. this.isOGGsupported = false;
  57923. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57924. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57925. this.canUseWebAudio = true;
  57926. }
  57927. var audioElem = document.createElement('audio');
  57928. try {
  57929. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57930. this.isMP3supported = true;
  57931. }
  57932. }
  57933. catch (e) {
  57934. // protect error during capability check.
  57935. }
  57936. try {
  57937. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57938. this.isOGGsupported = true;
  57939. }
  57940. }
  57941. catch (e) {
  57942. // protect error during capability check.
  57943. }
  57944. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57945. this._unlockiOSaudio();
  57946. }
  57947. else {
  57948. this.unlocked = true;
  57949. }
  57950. }
  57951. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57952. get: function () {
  57953. if (!this._audioContextInitialized) {
  57954. this._initializeAudioContext();
  57955. }
  57956. return this._audioContext;
  57957. },
  57958. enumerable: true,
  57959. configurable: true
  57960. });
  57961. AudioEngine.prototype._unlockiOSaudio = function () {
  57962. var _this = this;
  57963. var unlockaudio = function () {
  57964. if (!_this.audioContext) {
  57965. return;
  57966. }
  57967. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57968. var source = _this.audioContext.createBufferSource();
  57969. source.buffer = buffer;
  57970. source.connect(_this.audioContext.destination);
  57971. source.start(0);
  57972. setTimeout(function () {
  57973. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57974. _this.unlocked = true;
  57975. window.removeEventListener('touchend', unlockaudio, false);
  57976. if (_this.onAudioUnlocked) {
  57977. _this.onAudioUnlocked();
  57978. }
  57979. }
  57980. }, 0);
  57981. };
  57982. window.addEventListener('touchend', unlockaudio, false);
  57983. };
  57984. AudioEngine.prototype._initializeAudioContext = function () {
  57985. try {
  57986. if (this.canUseWebAudio) {
  57987. this._audioContext = new AudioContext();
  57988. // create a global volume gain node
  57989. this.masterGain = this._audioContext.createGain();
  57990. this.masterGain.gain.value = 1;
  57991. this.masterGain.connect(this._audioContext.destination);
  57992. this._audioContextInitialized = true;
  57993. }
  57994. }
  57995. catch (e) {
  57996. this.canUseWebAudio = false;
  57997. BABYLON.Tools.Error("Web Audio: " + e.message);
  57998. }
  57999. };
  58000. AudioEngine.prototype.dispose = function () {
  58001. if (this.canUseWebAudio && this._audioContextInitialized) {
  58002. if (this._connectedAnalyser && this._audioContext) {
  58003. this._connectedAnalyser.stopDebugCanvas();
  58004. this._connectedAnalyser.dispose();
  58005. this.masterGain.disconnect();
  58006. this.masterGain.connect(this._audioContext.destination);
  58007. this._connectedAnalyser = null;
  58008. }
  58009. this.masterGain.gain.value = 1;
  58010. }
  58011. this.WarnedWebAudioUnsupported = false;
  58012. };
  58013. AudioEngine.prototype.getGlobalVolume = function () {
  58014. if (this.canUseWebAudio && this._audioContextInitialized) {
  58015. return this.masterGain.gain.value;
  58016. }
  58017. else {
  58018. return -1;
  58019. }
  58020. };
  58021. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  58022. if (this.canUseWebAudio && this._audioContextInitialized) {
  58023. this.masterGain.gain.value = newVolume;
  58024. }
  58025. };
  58026. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  58027. if (this._connectedAnalyser) {
  58028. this._connectedAnalyser.stopDebugCanvas();
  58029. }
  58030. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  58031. this._connectedAnalyser = analyser;
  58032. this.masterGain.disconnect();
  58033. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  58034. }
  58035. };
  58036. return AudioEngine;
  58037. }());
  58038. BABYLON.AudioEngine = AudioEngine;
  58039. })(BABYLON || (BABYLON = {}));
  58040. //# sourceMappingURL=babylon.audioEngine.js.map
  58041. "use strict";
  58042. var BABYLON;
  58043. (function (BABYLON) {
  58044. var Sound = /** @class */ (function () {
  58045. /**
  58046. * Create a sound and attach it to a scene
  58047. * @param name Name of your sound
  58048. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  58049. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  58050. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  58051. */
  58052. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  58053. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  58054. var _this = this;
  58055. this.autoplay = false;
  58056. this.loop = false;
  58057. this.useCustomAttenuation = false;
  58058. this.spatialSound = false;
  58059. this.refDistance = 1;
  58060. this.rolloffFactor = 1;
  58061. this.maxDistance = 100;
  58062. this.distanceModel = "linear";
  58063. this._panningModel = "equalpower";
  58064. this._playbackRate = 1;
  58065. this._streaming = false;
  58066. this._startTime = 0;
  58067. this._startOffset = 0;
  58068. this._position = BABYLON.Vector3.Zero();
  58069. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  58070. this._volume = 1;
  58071. this._isReadyToPlay = false;
  58072. this.isPlaying = false;
  58073. this.isPaused = false;
  58074. this._isDirectional = false;
  58075. // Used if you'd like to create a directional sound.
  58076. // If not set, the sound will be omnidirectional
  58077. this._coneInnerAngle = 360;
  58078. this._coneOuterAngle = 360;
  58079. this._coneOuterGain = 0;
  58080. this._isOutputConnected = false;
  58081. this._urlType = "Unknown";
  58082. this.name = name;
  58083. this._scene = scene;
  58084. this._readyToPlayCallback = readyToPlayCallback;
  58085. // Default custom attenuation function is a linear attenuation
  58086. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  58087. if (currentDistance < maxDistance) {
  58088. return currentVolume * (1 - currentDistance / maxDistance);
  58089. }
  58090. else {
  58091. return 0;
  58092. }
  58093. };
  58094. if (options) {
  58095. this.autoplay = options.autoplay || false;
  58096. this.loop = options.loop || false;
  58097. // if volume === 0, we need another way to check this option
  58098. if (options.volume !== undefined) {
  58099. this._volume = options.volume;
  58100. }
  58101. this.spatialSound = options.spatialSound || false;
  58102. this.maxDistance = options.maxDistance || 100;
  58103. this.useCustomAttenuation = options.useCustomAttenuation || false;
  58104. this.rolloffFactor = options.rolloffFactor || 1;
  58105. this.refDistance = options.refDistance || 1;
  58106. this.distanceModel = options.distanceModel || "linear";
  58107. this._playbackRate = options.playbackRate || 1;
  58108. this._streaming = options.streaming || false;
  58109. }
  58110. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58111. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  58112. this._soundGain.gain.value = this._volume;
  58113. this._inputAudioNode = this._soundGain;
  58114. this._ouputAudioNode = this._soundGain;
  58115. if (this.spatialSound) {
  58116. this._createSpatialParameters();
  58117. }
  58118. this._scene.mainSoundTrack.AddSound(this);
  58119. var validParameter = true;
  58120. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  58121. if (urlOrArrayBuffer) {
  58122. try {
  58123. if (typeof (urlOrArrayBuffer) === "string")
  58124. this._urlType = "String";
  58125. if (Array.isArray(urlOrArrayBuffer))
  58126. this._urlType = "Array";
  58127. if (urlOrArrayBuffer instanceof ArrayBuffer)
  58128. this._urlType = "ArrayBuffer";
  58129. var urls = [];
  58130. var codecSupportedFound = false;
  58131. switch (this._urlType) {
  58132. case "ArrayBuffer":
  58133. if (urlOrArrayBuffer.byteLength > 0) {
  58134. codecSupportedFound = true;
  58135. this._soundLoaded(urlOrArrayBuffer);
  58136. }
  58137. break;
  58138. case "String":
  58139. urls.push(urlOrArrayBuffer);
  58140. case "Array":
  58141. if (urls.length === 0)
  58142. urls = urlOrArrayBuffer;
  58143. // If we found a supported format, we load it immediately and stop the loop
  58144. for (var i = 0; i < urls.length; i++) {
  58145. var url = urls[i];
  58146. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  58147. codecSupportedFound = true;
  58148. }
  58149. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  58150. codecSupportedFound = true;
  58151. }
  58152. if (url.indexOf(".wav", url.length - 4) !== -1) {
  58153. codecSupportedFound = true;
  58154. }
  58155. if (url.indexOf("blob:") !== -1) {
  58156. codecSupportedFound = true;
  58157. }
  58158. if (codecSupportedFound) {
  58159. // Loading sound using XHR2
  58160. if (!this._streaming) {
  58161. this._scene._loadFile(url, function (data) {
  58162. _this._soundLoaded(data);
  58163. }, undefined, true, true, function (exception) {
  58164. if (exception) {
  58165. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  58166. }
  58167. BABYLON.Tools.Error("Sound creation aborted.");
  58168. _this._scene.mainSoundTrack.RemoveSound(_this);
  58169. });
  58170. }
  58171. else {
  58172. this._htmlAudioElement = new Audio(url);
  58173. this._htmlAudioElement.controls = false;
  58174. this._htmlAudioElement.loop = this.loop;
  58175. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  58176. this._htmlAudioElement.preload = "auto";
  58177. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  58178. _this._isReadyToPlay = true;
  58179. if (_this.autoplay) {
  58180. _this.play();
  58181. }
  58182. if (_this._readyToPlayCallback) {
  58183. _this._readyToPlayCallback();
  58184. }
  58185. });
  58186. document.body.appendChild(this._htmlAudioElement);
  58187. }
  58188. break;
  58189. }
  58190. }
  58191. break;
  58192. default:
  58193. validParameter = false;
  58194. break;
  58195. }
  58196. if (!validParameter) {
  58197. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  58198. }
  58199. else {
  58200. if (!codecSupportedFound) {
  58201. this._isReadyToPlay = true;
  58202. // Simulating a ready to play event to avoid breaking code path
  58203. if (this._readyToPlayCallback) {
  58204. window.setTimeout(function () {
  58205. if (_this._readyToPlayCallback) {
  58206. _this._readyToPlayCallback();
  58207. }
  58208. }, 1000);
  58209. }
  58210. }
  58211. }
  58212. }
  58213. catch (ex) {
  58214. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  58215. this._scene.mainSoundTrack.RemoveSound(this);
  58216. }
  58217. }
  58218. }
  58219. else {
  58220. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  58221. this._scene.mainSoundTrack.AddSound(this);
  58222. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  58223. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  58224. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  58225. }
  58226. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  58227. if (this._readyToPlayCallback) {
  58228. window.setTimeout(function () {
  58229. if (_this._readyToPlayCallback) {
  58230. _this._readyToPlayCallback();
  58231. }
  58232. }, 1000);
  58233. }
  58234. }
  58235. }
  58236. Sound.prototype.dispose = function () {
  58237. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58238. if (this.isPlaying) {
  58239. this.stop();
  58240. }
  58241. this._isReadyToPlay = false;
  58242. if (this.soundTrackId === -1) {
  58243. this._scene.mainSoundTrack.RemoveSound(this);
  58244. }
  58245. else {
  58246. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58247. }
  58248. if (this._soundGain) {
  58249. this._soundGain.disconnect();
  58250. this._soundGain = null;
  58251. }
  58252. if (this._soundPanner) {
  58253. this._soundPanner.disconnect();
  58254. this._soundPanner = null;
  58255. }
  58256. if (this._soundSource) {
  58257. this._soundSource.disconnect();
  58258. this._soundSource = null;
  58259. }
  58260. this._audioBuffer = null;
  58261. if (this._htmlAudioElement) {
  58262. this._htmlAudioElement.pause();
  58263. this._htmlAudioElement.src = "";
  58264. document.body.removeChild(this._htmlAudioElement);
  58265. }
  58266. if (this._connectedMesh && this._registerFunc) {
  58267. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58268. this._connectedMesh = null;
  58269. }
  58270. }
  58271. };
  58272. Sound.prototype.isReady = function () {
  58273. return this._isReadyToPlay;
  58274. };
  58275. Sound.prototype._soundLoaded = function (audioData) {
  58276. var _this = this;
  58277. if (!BABYLON.Engine.audioEngine.audioContext) {
  58278. return;
  58279. }
  58280. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58281. _this._audioBuffer = buffer;
  58282. _this._isReadyToPlay = true;
  58283. if (_this.autoplay) {
  58284. _this.play();
  58285. }
  58286. if (_this._readyToPlayCallback) {
  58287. _this._readyToPlayCallback();
  58288. }
  58289. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58290. };
  58291. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58292. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58293. this._audioBuffer = audioBuffer;
  58294. this._isReadyToPlay = true;
  58295. }
  58296. };
  58297. Sound.prototype.updateOptions = function (options) {
  58298. if (options) {
  58299. this.loop = options.loop || this.loop;
  58300. this.maxDistance = options.maxDistance || this.maxDistance;
  58301. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58302. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58303. this.refDistance = options.refDistance || this.refDistance;
  58304. this.distanceModel = options.distanceModel || this.distanceModel;
  58305. this._playbackRate = options.playbackRate || this._playbackRate;
  58306. this._updateSpatialParameters();
  58307. if (this.isPlaying) {
  58308. if (this._streaming) {
  58309. this._htmlAudioElement.playbackRate = this._playbackRate;
  58310. }
  58311. else {
  58312. if (this._soundSource) {
  58313. this._soundSource.playbackRate.value = this._playbackRate;
  58314. }
  58315. }
  58316. }
  58317. }
  58318. };
  58319. Sound.prototype._createSpatialParameters = function () {
  58320. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58321. if (this._scene.headphone) {
  58322. this._panningModel = "HRTF";
  58323. }
  58324. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58325. this._updateSpatialParameters();
  58326. this._soundPanner.connect(this._ouputAudioNode);
  58327. this._inputAudioNode = this._soundPanner;
  58328. }
  58329. };
  58330. Sound.prototype._updateSpatialParameters = function () {
  58331. if (this.spatialSound && this._soundPanner) {
  58332. if (this.useCustomAttenuation) {
  58333. // Tricks to disable in a way embedded Web Audio attenuation
  58334. this._soundPanner.distanceModel = "linear";
  58335. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58336. this._soundPanner.refDistance = 1;
  58337. this._soundPanner.rolloffFactor = 1;
  58338. this._soundPanner.panningModel = this._panningModel;
  58339. }
  58340. else {
  58341. this._soundPanner.distanceModel = this.distanceModel;
  58342. this._soundPanner.maxDistance = this.maxDistance;
  58343. this._soundPanner.refDistance = this.refDistance;
  58344. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58345. this._soundPanner.panningModel = this._panningModel;
  58346. }
  58347. }
  58348. };
  58349. Sound.prototype.switchPanningModelToHRTF = function () {
  58350. this._panningModel = "HRTF";
  58351. this._switchPanningModel();
  58352. };
  58353. Sound.prototype.switchPanningModelToEqualPower = function () {
  58354. this._panningModel = "equalpower";
  58355. this._switchPanningModel();
  58356. };
  58357. Sound.prototype._switchPanningModel = function () {
  58358. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58359. this._soundPanner.panningModel = this._panningModel;
  58360. }
  58361. };
  58362. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58363. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58364. if (this._isOutputConnected) {
  58365. this._ouputAudioNode.disconnect();
  58366. }
  58367. this._ouputAudioNode.connect(soundTrackAudioNode);
  58368. this._isOutputConnected = true;
  58369. }
  58370. };
  58371. /**
  58372. * Transform this sound into a directional source
  58373. * @param coneInnerAngle Size of the inner cone in degree
  58374. * @param coneOuterAngle Size of the outer cone in degree
  58375. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58376. */
  58377. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58378. if (coneOuterAngle < coneInnerAngle) {
  58379. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58380. return;
  58381. }
  58382. this._coneInnerAngle = coneInnerAngle;
  58383. this._coneOuterAngle = coneOuterAngle;
  58384. this._coneOuterGain = coneOuterGain;
  58385. this._isDirectional = true;
  58386. if (this.isPlaying && this.loop) {
  58387. this.stop();
  58388. this.play();
  58389. }
  58390. };
  58391. Sound.prototype.setPosition = function (newPosition) {
  58392. this._position = newPosition;
  58393. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58394. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58395. }
  58396. };
  58397. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58398. this._localDirection = newLocalDirection;
  58399. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58400. this._updateDirection();
  58401. }
  58402. };
  58403. Sound.prototype._updateDirection = function () {
  58404. if (!this._connectedMesh || !this._soundPanner) {
  58405. return;
  58406. }
  58407. var mat = this._connectedMesh.getWorldMatrix();
  58408. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58409. direction.normalize();
  58410. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58411. };
  58412. Sound.prototype.updateDistanceFromListener = function () {
  58413. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58414. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58415. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58416. }
  58417. };
  58418. Sound.prototype.setAttenuationFunction = function (callback) {
  58419. this._customAttenuationFunction = callback;
  58420. };
  58421. /**
  58422. * Play the sound
  58423. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58424. * @param offset (optional) Start the sound setting it at a specific time
  58425. */
  58426. Sound.prototype.play = function (time, offset) {
  58427. var _this = this;
  58428. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58429. try {
  58430. if (this._startOffset < 0) {
  58431. time = -this._startOffset;
  58432. this._startOffset = 0;
  58433. }
  58434. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58435. if (!this._soundSource || !this._streamingSource) {
  58436. if (this.spatialSound && this._soundPanner) {
  58437. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58438. if (this._isDirectional) {
  58439. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58440. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58441. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58442. if (this._connectedMesh) {
  58443. this._updateDirection();
  58444. }
  58445. else {
  58446. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58447. }
  58448. }
  58449. }
  58450. }
  58451. if (this._streaming) {
  58452. if (!this._streamingSource) {
  58453. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58454. this._htmlAudioElement.onended = function () { _this._onended(); };
  58455. this._htmlAudioElement.playbackRate = this._playbackRate;
  58456. }
  58457. this._streamingSource.disconnect();
  58458. this._streamingSource.connect(this._inputAudioNode);
  58459. this._htmlAudioElement.play();
  58460. }
  58461. else {
  58462. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58463. this._soundSource.buffer = this._audioBuffer;
  58464. this._soundSource.connect(this._inputAudioNode);
  58465. this._soundSource.loop = this.loop;
  58466. this._soundSource.playbackRate.value = this._playbackRate;
  58467. this._soundSource.onended = function () { _this._onended(); };
  58468. if (this._soundSource.buffer) {
  58469. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58470. }
  58471. }
  58472. this._startTime = startTime;
  58473. this.isPlaying = true;
  58474. this.isPaused = false;
  58475. }
  58476. catch (ex) {
  58477. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58478. }
  58479. }
  58480. };
  58481. Sound.prototype._onended = function () {
  58482. this.isPlaying = false;
  58483. if (this.onended) {
  58484. this.onended();
  58485. }
  58486. };
  58487. /**
  58488. * Stop the sound
  58489. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58490. */
  58491. Sound.prototype.stop = function (time) {
  58492. if (this.isPlaying) {
  58493. if (this._streaming) {
  58494. this._htmlAudioElement.pause();
  58495. // Test needed for Firefox or it will generate an Invalid State Error
  58496. if (this._htmlAudioElement.currentTime > 0) {
  58497. this._htmlAudioElement.currentTime = 0;
  58498. }
  58499. }
  58500. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58501. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58502. this._soundSource.stop(stopTime);
  58503. this._soundSource.onended = function () { };
  58504. if (!this.isPaused) {
  58505. this._startOffset = 0;
  58506. }
  58507. }
  58508. this.isPlaying = false;
  58509. }
  58510. };
  58511. Sound.prototype.pause = function () {
  58512. if (this.isPlaying) {
  58513. this.isPaused = true;
  58514. if (this._streaming) {
  58515. this._htmlAudioElement.pause();
  58516. }
  58517. else if (BABYLON.Engine.audioEngine.audioContext) {
  58518. this.stop(0);
  58519. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58520. }
  58521. }
  58522. };
  58523. Sound.prototype.setVolume = function (newVolume, time) {
  58524. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58525. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58526. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58527. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58528. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58529. }
  58530. else {
  58531. this._soundGain.gain.value = newVolume;
  58532. }
  58533. }
  58534. this._volume = newVolume;
  58535. };
  58536. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58537. this._playbackRate = newPlaybackRate;
  58538. if (this.isPlaying) {
  58539. if (this._streaming) {
  58540. this._htmlAudioElement.playbackRate = this._playbackRate;
  58541. }
  58542. else if (this._soundSource) {
  58543. this._soundSource.playbackRate.value = this._playbackRate;
  58544. }
  58545. }
  58546. };
  58547. Sound.prototype.getVolume = function () {
  58548. return this._volume;
  58549. };
  58550. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58551. var _this = this;
  58552. if (this._connectedMesh && this._registerFunc) {
  58553. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58554. this._registerFunc = null;
  58555. }
  58556. this._connectedMesh = meshToConnectTo;
  58557. if (!this.spatialSound) {
  58558. this.spatialSound = true;
  58559. this._createSpatialParameters();
  58560. if (this.isPlaying && this.loop) {
  58561. this.stop();
  58562. this.play();
  58563. }
  58564. }
  58565. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58566. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58567. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58568. };
  58569. Sound.prototype.detachFromMesh = function () {
  58570. if (this._connectedMesh && this._registerFunc) {
  58571. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58572. this._registerFunc = null;
  58573. this._connectedMesh = null;
  58574. }
  58575. };
  58576. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58577. if (!node.getBoundingInfo) {
  58578. return;
  58579. }
  58580. var mesh = node;
  58581. var boundingInfo = mesh.getBoundingInfo();
  58582. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58583. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58584. this._updateDirection();
  58585. }
  58586. };
  58587. Sound.prototype.clone = function () {
  58588. var _this = this;
  58589. if (!this._streaming) {
  58590. var setBufferAndRun = function () {
  58591. if (_this._isReadyToPlay) {
  58592. clonedSound._audioBuffer = _this.getAudioBuffer();
  58593. clonedSound._isReadyToPlay = true;
  58594. if (clonedSound.autoplay) {
  58595. clonedSound.play();
  58596. }
  58597. }
  58598. else {
  58599. window.setTimeout(setBufferAndRun, 300);
  58600. }
  58601. };
  58602. var currentOptions = {
  58603. autoplay: this.autoplay, loop: this.loop,
  58604. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58605. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58606. refDistance: this.refDistance, distanceModel: this.distanceModel
  58607. };
  58608. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58609. if (this.useCustomAttenuation) {
  58610. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58611. }
  58612. clonedSound.setPosition(this._position);
  58613. clonedSound.setPlaybackRate(this._playbackRate);
  58614. setBufferAndRun();
  58615. return clonedSound;
  58616. }
  58617. else {
  58618. return null;
  58619. }
  58620. };
  58621. Sound.prototype.getAudioBuffer = function () {
  58622. return this._audioBuffer;
  58623. };
  58624. Sound.prototype.serialize = function () {
  58625. var serializationObject = {
  58626. name: this.name,
  58627. url: this.name,
  58628. autoplay: this.autoplay,
  58629. loop: this.loop,
  58630. volume: this._volume,
  58631. spatialSound: this.spatialSound,
  58632. maxDistance: this.maxDistance,
  58633. rolloffFactor: this.rolloffFactor,
  58634. refDistance: this.refDistance,
  58635. distanceModel: this.distanceModel,
  58636. playbackRate: this._playbackRate,
  58637. panningModel: this._panningModel,
  58638. soundTrackId: this.soundTrackId
  58639. };
  58640. if (this.spatialSound) {
  58641. if (this._connectedMesh)
  58642. serializationObject.connectedMeshId = this._connectedMesh.id;
  58643. serializationObject.position = this._position.asArray();
  58644. serializationObject.refDistance = this.refDistance;
  58645. serializationObject.distanceModel = this.distanceModel;
  58646. serializationObject.isDirectional = this._isDirectional;
  58647. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58648. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58649. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58650. serializationObject.coneOuterGain = this._coneOuterGain;
  58651. }
  58652. return serializationObject;
  58653. };
  58654. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58655. var soundName = parsedSound.name;
  58656. var soundUrl;
  58657. if (parsedSound.url) {
  58658. soundUrl = rootUrl + parsedSound.url;
  58659. }
  58660. else {
  58661. soundUrl = rootUrl + soundName;
  58662. }
  58663. var options = {
  58664. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58665. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58666. rolloffFactor: parsedSound.rolloffFactor,
  58667. refDistance: parsedSound.refDistance,
  58668. distanceModel: parsedSound.distanceModel,
  58669. playbackRate: parsedSound.playbackRate
  58670. };
  58671. var newSound;
  58672. if (!sourceSound) {
  58673. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58674. scene._addPendingData(newSound);
  58675. }
  58676. else {
  58677. var setBufferAndRun = function () {
  58678. if (sourceSound._isReadyToPlay) {
  58679. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58680. newSound._isReadyToPlay = true;
  58681. if (newSound.autoplay) {
  58682. newSound.play();
  58683. }
  58684. }
  58685. else {
  58686. window.setTimeout(setBufferAndRun, 300);
  58687. }
  58688. };
  58689. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58690. setBufferAndRun();
  58691. }
  58692. if (parsedSound.position) {
  58693. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58694. newSound.setPosition(soundPosition);
  58695. }
  58696. if (parsedSound.isDirectional) {
  58697. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58698. if (parsedSound.localDirectionToMesh) {
  58699. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58700. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58701. }
  58702. }
  58703. if (parsedSound.connectedMeshId) {
  58704. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58705. if (connectedMesh) {
  58706. newSound.attachToMesh(connectedMesh);
  58707. }
  58708. }
  58709. return newSound;
  58710. };
  58711. return Sound;
  58712. }());
  58713. BABYLON.Sound = Sound;
  58714. })(BABYLON || (BABYLON = {}));
  58715. //# sourceMappingURL=babylon.sound.js.map
  58716. "use strict";
  58717. var BABYLON;
  58718. (function (BABYLON) {
  58719. var SoundTrack = /** @class */ (function () {
  58720. function SoundTrack(scene, options) {
  58721. this.id = -1;
  58722. this._isMainTrack = false;
  58723. this._isInitialized = false;
  58724. this._scene = scene;
  58725. this.soundCollection = new Array();
  58726. this._options = options;
  58727. if (!this._isMainTrack) {
  58728. this._scene.soundTracks.push(this);
  58729. this.id = this._scene.soundTracks.length - 1;
  58730. }
  58731. }
  58732. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58733. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58734. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58735. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58736. if (this._options) {
  58737. if (this._options.volume) {
  58738. this._outputAudioNode.gain.value = this._options.volume;
  58739. }
  58740. if (this._options.mainTrack) {
  58741. this._isMainTrack = this._options.mainTrack;
  58742. }
  58743. }
  58744. this._isInitialized = true;
  58745. }
  58746. };
  58747. SoundTrack.prototype.dispose = function () {
  58748. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58749. if (this._connectedAnalyser) {
  58750. this._connectedAnalyser.stopDebugCanvas();
  58751. }
  58752. while (this.soundCollection.length) {
  58753. this.soundCollection[0].dispose();
  58754. }
  58755. if (this._outputAudioNode) {
  58756. this._outputAudioNode.disconnect();
  58757. }
  58758. this._outputAudioNode = null;
  58759. }
  58760. };
  58761. SoundTrack.prototype.AddSound = function (sound) {
  58762. if (!this._isInitialized) {
  58763. this._initializeSoundTrackAudioGraph();
  58764. }
  58765. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58766. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58767. }
  58768. if (sound.soundTrackId) {
  58769. if (sound.soundTrackId === -1) {
  58770. this._scene.mainSoundTrack.RemoveSound(sound);
  58771. }
  58772. else {
  58773. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58774. }
  58775. }
  58776. this.soundCollection.push(sound);
  58777. sound.soundTrackId = this.id;
  58778. };
  58779. SoundTrack.prototype.RemoveSound = function (sound) {
  58780. var index = this.soundCollection.indexOf(sound);
  58781. if (index !== -1) {
  58782. this.soundCollection.splice(index, 1);
  58783. }
  58784. };
  58785. SoundTrack.prototype.setVolume = function (newVolume) {
  58786. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58787. this._outputAudioNode.gain.value = newVolume;
  58788. }
  58789. };
  58790. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58791. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58792. for (var i = 0; i < this.soundCollection.length; i++) {
  58793. this.soundCollection[i].switchPanningModelToHRTF();
  58794. }
  58795. }
  58796. };
  58797. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58798. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58799. for (var i = 0; i < this.soundCollection.length; i++) {
  58800. this.soundCollection[i].switchPanningModelToEqualPower();
  58801. }
  58802. }
  58803. };
  58804. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58805. if (this._connectedAnalyser) {
  58806. this._connectedAnalyser.stopDebugCanvas();
  58807. }
  58808. this._connectedAnalyser = analyser;
  58809. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58810. this._outputAudioNode.disconnect();
  58811. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58812. }
  58813. };
  58814. return SoundTrack;
  58815. }());
  58816. BABYLON.SoundTrack = SoundTrack;
  58817. })(BABYLON || (BABYLON = {}));
  58818. //# sourceMappingURL=babylon.soundtrack.js.map
  58819. "use strict";
  58820. var BABYLON;
  58821. (function (BABYLON) {
  58822. var Analyser = /** @class */ (function () {
  58823. function Analyser(scene) {
  58824. this.SMOOTHING = 0.75;
  58825. this.FFT_SIZE = 512;
  58826. this.BARGRAPHAMPLITUDE = 256;
  58827. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58828. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58829. this._scene = scene;
  58830. this._audioEngine = BABYLON.Engine.audioEngine;
  58831. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58832. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58833. this._webAudioAnalyser.minDecibels = -140;
  58834. this._webAudioAnalyser.maxDecibels = 0;
  58835. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58836. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58837. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58838. }
  58839. }
  58840. Analyser.prototype.getFrequencyBinCount = function () {
  58841. if (this._audioEngine.canUseWebAudio) {
  58842. return this._webAudioAnalyser.frequencyBinCount;
  58843. }
  58844. else {
  58845. return 0;
  58846. }
  58847. };
  58848. Analyser.prototype.getByteFrequencyData = function () {
  58849. if (this._audioEngine.canUseWebAudio) {
  58850. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58851. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58852. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58853. }
  58854. return this._byteFreqs;
  58855. };
  58856. Analyser.prototype.getByteTimeDomainData = function () {
  58857. if (this._audioEngine.canUseWebAudio) {
  58858. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58859. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58860. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58861. }
  58862. return this._byteTime;
  58863. };
  58864. Analyser.prototype.getFloatFrequencyData = function () {
  58865. if (this._audioEngine.canUseWebAudio) {
  58866. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58867. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58868. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58869. }
  58870. return this._floatFreqs;
  58871. };
  58872. Analyser.prototype.drawDebugCanvas = function () {
  58873. var _this = this;
  58874. if (this._audioEngine.canUseWebAudio) {
  58875. if (!this._debugCanvas) {
  58876. this._debugCanvas = document.createElement("canvas");
  58877. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58878. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58879. this._debugCanvas.style.position = "absolute";
  58880. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58881. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58882. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58883. document.body.appendChild(this._debugCanvas);
  58884. this._registerFunc = function () {
  58885. _this.drawDebugCanvas();
  58886. };
  58887. this._scene.registerBeforeRender(this._registerFunc);
  58888. }
  58889. if (this._registerFunc && this._debugCanvasContext) {
  58890. var workingArray = this.getByteFrequencyData();
  58891. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58892. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58893. // Draw the frequency domain chart.
  58894. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58895. var value = workingArray[i];
  58896. var percent = value / this.BARGRAPHAMPLITUDE;
  58897. var height = this.DEBUGCANVASSIZE.height * percent;
  58898. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58899. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58900. var hue = i / this.getFrequencyBinCount() * 360;
  58901. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58902. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58903. }
  58904. }
  58905. }
  58906. };
  58907. Analyser.prototype.stopDebugCanvas = function () {
  58908. if (this._debugCanvas) {
  58909. if (this._registerFunc) {
  58910. this._scene.unregisterBeforeRender(this._registerFunc);
  58911. this._registerFunc = null;
  58912. }
  58913. document.body.removeChild(this._debugCanvas);
  58914. this._debugCanvas = null;
  58915. this._debugCanvasContext = null;
  58916. }
  58917. };
  58918. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58919. if (this._audioEngine.canUseWebAudio) {
  58920. inputAudioNode.connect(this._webAudioAnalyser);
  58921. this._webAudioAnalyser.connect(outputAudioNode);
  58922. }
  58923. };
  58924. Analyser.prototype.dispose = function () {
  58925. if (this._audioEngine.canUseWebAudio) {
  58926. this._webAudioAnalyser.disconnect();
  58927. }
  58928. };
  58929. return Analyser;
  58930. }());
  58931. BABYLON.Analyser = Analyser;
  58932. })(BABYLON || (BABYLON = {}));
  58933. //# sourceMappingURL=babylon.analyser.js.map
  58934. "use strict";
  58935. var BABYLON;
  58936. (function (BABYLON) {
  58937. var CubeTexture = /** @class */ (function (_super) {
  58938. __extends(CubeTexture, _super);
  58939. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58940. if (extensions === void 0) { extensions = null; }
  58941. if (noMipmap === void 0) { noMipmap = false; }
  58942. if (files === void 0) { files = null; }
  58943. if (onLoad === void 0) { onLoad = null; }
  58944. if (onError === void 0) { onError = null; }
  58945. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58946. if (prefiltered === void 0) { prefiltered = false; }
  58947. if (forcedExtension === void 0) { forcedExtension = null; }
  58948. var _this = _super.call(this, scene) || this;
  58949. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58950. /**
  58951. * Gets or sets the center of the bounding box associated with the cube texture
  58952. * It must define where the camera used to render the texture was set
  58953. */
  58954. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58955. _this.name = rootUrl;
  58956. _this.url = rootUrl;
  58957. _this._noMipmap = noMipmap;
  58958. _this.hasAlpha = false;
  58959. _this._format = format;
  58960. _this._prefiltered = prefiltered;
  58961. _this.isCube = true;
  58962. _this._textureMatrix = BABYLON.Matrix.Identity();
  58963. if (prefiltered) {
  58964. _this.gammaSpace = false;
  58965. }
  58966. if (!rootUrl && !files) {
  58967. return _this;
  58968. }
  58969. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58970. var lastDot = rootUrl.lastIndexOf(".");
  58971. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58972. var isDDS = (extension === ".dds");
  58973. if (!files) {
  58974. if (!isDDS && !extensions) {
  58975. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58976. }
  58977. files = [];
  58978. if (extensions) {
  58979. for (var index = 0; index < extensions.length; index++) {
  58980. files.push(rootUrl + extensions[index]);
  58981. }
  58982. }
  58983. }
  58984. _this._files = files;
  58985. if (!_this._texture) {
  58986. if (!scene.useDelayedTextureLoading) {
  58987. if (prefiltered) {
  58988. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58989. }
  58990. else {
  58991. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58992. }
  58993. }
  58994. else {
  58995. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58996. }
  58997. }
  58998. else if (onLoad) {
  58999. if (_this._texture.isReady) {
  59000. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  59001. }
  59002. else {
  59003. _this._texture.onLoadedObservable.add(onLoad);
  59004. }
  59005. }
  59006. return _this;
  59007. }
  59008. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  59009. get: function () {
  59010. return this._boundingBoxSize;
  59011. },
  59012. /**
  59013. * Gets or sets the size of the bounding box associated with the cube texture
  59014. * When defined, the cubemap will switch to local mode
  59015. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59016. * @example https://www.babylonjs-playground.com/#RNASML
  59017. */
  59018. set: function (value) {
  59019. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59020. return;
  59021. }
  59022. this._boundingBoxSize = value;
  59023. var scene = this.getScene();
  59024. if (scene) {
  59025. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59026. }
  59027. },
  59028. enumerable: true,
  59029. configurable: true
  59030. });
  59031. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  59032. var rootUrlKey = "";
  59033. files.forEach(function (url) { return rootUrlKey += url; });
  59034. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  59035. };
  59036. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  59037. if (forcedExtension === void 0) { forcedExtension = null; }
  59038. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  59039. };
  59040. // Methods
  59041. CubeTexture.prototype.delayLoad = function () {
  59042. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59043. return;
  59044. }
  59045. var scene = this.getScene();
  59046. if (!scene) {
  59047. return;
  59048. }
  59049. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59050. this._texture = this._getFromCache(this.url, this._noMipmap);
  59051. if (!this._texture) {
  59052. if (this._prefiltered) {
  59053. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  59054. }
  59055. else {
  59056. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  59057. }
  59058. }
  59059. };
  59060. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  59061. return this._textureMatrix;
  59062. };
  59063. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59064. this._textureMatrix = value;
  59065. };
  59066. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59067. var texture = BABYLON.SerializationHelper.Parse(function () {
  59068. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  59069. }, parsedTexture, scene);
  59070. // Local Cubemaps
  59071. if (parsedTexture.boundingBoxPosition) {
  59072. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  59073. }
  59074. if (parsedTexture.boundingBoxSize) {
  59075. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  59076. }
  59077. // Animations
  59078. if (parsedTexture.animations) {
  59079. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  59080. var parsedAnimation = parsedTexture.animations[animationIndex];
  59081. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59082. }
  59083. }
  59084. return texture;
  59085. };
  59086. CubeTexture.prototype.clone = function () {
  59087. var _this = this;
  59088. return BABYLON.SerializationHelper.Clone(function () {
  59089. var scene = _this.getScene();
  59090. if (!scene) {
  59091. return _this;
  59092. }
  59093. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  59094. }, this);
  59095. };
  59096. return CubeTexture;
  59097. }(BABYLON.BaseTexture));
  59098. BABYLON.CubeTexture = CubeTexture;
  59099. })(BABYLON || (BABYLON = {}));
  59100. //# sourceMappingURL=babylon.cubeTexture.js.map
  59101. "use strict";
  59102. var BABYLON;
  59103. (function (BABYLON) {
  59104. var RenderTargetTexture = /** @class */ (function (_super) {
  59105. __extends(RenderTargetTexture, _super);
  59106. /**
  59107. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  59108. * or used a shadow, depth texture...
  59109. * @param name The friendly name of the texture
  59110. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  59111. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  59112. * @param generateMipMaps True if mip maps need to be generated after render.
  59113. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  59114. * @param type The type of the buffer in the RTT (int, half float, float...)
  59115. * @param isCube True if a cube texture needs to be created
  59116. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  59117. * @param generateDepthBuffer True to generate a depth buffer
  59118. * @param generateStencilBuffer True to generate a stencil buffer
  59119. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  59120. */
  59121. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  59122. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  59123. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59124. if (isCube === void 0) { isCube = false; }
  59125. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59126. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59127. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  59128. if (isMulti === void 0) { isMulti = false; }
  59129. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59130. _this.isCube = isCube;
  59131. /**
  59132. * Use this list to define the list of mesh you want to render.
  59133. */
  59134. _this.renderList = new Array();
  59135. _this.renderParticles = true;
  59136. _this.renderSprites = false;
  59137. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  59138. _this.ignoreCameraViewport = false;
  59139. // Events
  59140. /**
  59141. * An event triggered when the texture is unbind.
  59142. * @type {BABYLON.Observable}
  59143. */
  59144. _this.onBeforeBindObservable = new BABYLON.Observable();
  59145. /**
  59146. * An event triggered when the texture is unbind.
  59147. * @type {BABYLON.Observable}
  59148. */
  59149. _this.onAfterUnbindObservable = new BABYLON.Observable();
  59150. /**
  59151. * An event triggered before rendering the texture
  59152. * @type {BABYLON.Observable}
  59153. */
  59154. _this.onBeforeRenderObservable = new BABYLON.Observable();
  59155. /**
  59156. * An event triggered after rendering the texture
  59157. * @type {BABYLON.Observable}
  59158. */
  59159. _this.onAfterRenderObservable = new BABYLON.Observable();
  59160. /**
  59161. * An event triggered after the texture clear
  59162. * @type {BABYLON.Observable}
  59163. */
  59164. _this.onClearObservable = new BABYLON.Observable();
  59165. _this._currentRefreshId = -1;
  59166. _this._refreshRate = 1;
  59167. _this._samples = 1;
  59168. /**
  59169. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  59170. * It must define where the camera used to render the texture is set
  59171. */
  59172. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59173. scene = _this.getScene();
  59174. if (!scene) {
  59175. return _this;
  59176. }
  59177. _this._engine = scene.getEngine();
  59178. _this.name = name;
  59179. _this.isRenderTarget = true;
  59180. _this._initialSizeParameter = size;
  59181. _this._processSizeParameter(size);
  59182. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  59183. });
  59184. _this._generateMipMaps = generateMipMaps ? true : false;
  59185. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  59186. // Rendering groups
  59187. _this._renderingManager = new BABYLON.RenderingManager(scene);
  59188. if (isMulti) {
  59189. return _this;
  59190. }
  59191. _this._renderTargetOptions = {
  59192. generateMipMaps: generateMipMaps,
  59193. type: type,
  59194. samplingMode: samplingMode,
  59195. generateDepthBuffer: generateDepthBuffer,
  59196. generateStencilBuffer: generateStencilBuffer
  59197. };
  59198. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  59199. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59200. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59201. }
  59202. if (isCube) {
  59203. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  59204. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  59205. _this._textureMatrix = BABYLON.Matrix.Identity();
  59206. }
  59207. else {
  59208. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  59209. }
  59210. return _this;
  59211. }
  59212. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  59213. get: function () {
  59214. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  59215. },
  59216. enumerable: true,
  59217. configurable: true
  59218. });
  59219. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  59220. get: function () {
  59221. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  59222. },
  59223. enumerable: true,
  59224. configurable: true
  59225. });
  59226. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  59227. get: function () {
  59228. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  59229. },
  59230. enumerable: true,
  59231. configurable: true
  59232. });
  59233. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59234. set: function (callback) {
  59235. if (this._onAfterUnbindObserver) {
  59236. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59237. }
  59238. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59239. },
  59240. enumerable: true,
  59241. configurable: true
  59242. });
  59243. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59244. set: function (callback) {
  59245. if (this._onBeforeRenderObserver) {
  59246. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59247. }
  59248. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59249. },
  59250. enumerable: true,
  59251. configurable: true
  59252. });
  59253. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59254. set: function (callback) {
  59255. if (this._onAfterRenderObserver) {
  59256. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59257. }
  59258. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59259. },
  59260. enumerable: true,
  59261. configurable: true
  59262. });
  59263. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59264. set: function (callback) {
  59265. if (this._onClearObserver) {
  59266. this.onClearObservable.remove(this._onClearObserver);
  59267. }
  59268. this._onClearObserver = this.onClearObservable.add(callback);
  59269. },
  59270. enumerable: true,
  59271. configurable: true
  59272. });
  59273. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59274. get: function () {
  59275. return this._renderTargetOptions;
  59276. },
  59277. enumerable: true,
  59278. configurable: true
  59279. });
  59280. RenderTargetTexture.prototype._onRatioRescale = function () {
  59281. if (this._sizeRatio) {
  59282. this.resize(this._initialSizeParameter);
  59283. }
  59284. };
  59285. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59286. get: function () {
  59287. return this._boundingBoxSize;
  59288. },
  59289. /**
  59290. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59291. * When defined, the cubemap will switch to local mode
  59292. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59293. * @example https://www.babylonjs-playground.com/#RNASML
  59294. */
  59295. set: function (value) {
  59296. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59297. return;
  59298. }
  59299. this._boundingBoxSize = value;
  59300. var scene = this.getScene();
  59301. if (scene) {
  59302. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59303. }
  59304. },
  59305. enumerable: true,
  59306. configurable: true
  59307. });
  59308. /**
  59309. * Creates a depth stencil texture.
  59310. * This is only available in WebGL 2 or with the depth texture extension available.
  59311. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59312. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59313. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59314. */
  59315. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59316. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59317. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59318. if (generateStencil === void 0) { generateStencil = false; }
  59319. if (!this.getScene()) {
  59320. return;
  59321. }
  59322. var engine = this.getScene().getEngine();
  59323. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59324. bilinearFiltering: bilinearFiltering,
  59325. comparisonFunction: comparisonFunction,
  59326. generateStencil: generateStencil,
  59327. isCube: this.isCube
  59328. });
  59329. engine.setFrameBufferDepthStencilTexture(this);
  59330. };
  59331. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59332. if (size.ratio) {
  59333. this._sizeRatio = size.ratio;
  59334. this._size = {
  59335. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59336. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59337. };
  59338. }
  59339. else {
  59340. this._size = size;
  59341. }
  59342. };
  59343. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59344. get: function () {
  59345. return this._samples;
  59346. },
  59347. set: function (value) {
  59348. if (this._samples === value) {
  59349. return;
  59350. }
  59351. var scene = this.getScene();
  59352. if (!scene) {
  59353. return;
  59354. }
  59355. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59356. },
  59357. enumerable: true,
  59358. configurable: true
  59359. });
  59360. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59361. this._currentRefreshId = -1;
  59362. };
  59363. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59364. get: function () {
  59365. return this._refreshRate;
  59366. },
  59367. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59368. set: function (value) {
  59369. this._refreshRate = value;
  59370. this.resetRefreshCounter();
  59371. },
  59372. enumerable: true,
  59373. configurable: true
  59374. });
  59375. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59376. if (!this._postProcessManager) {
  59377. var scene = this.getScene();
  59378. if (!scene) {
  59379. return;
  59380. }
  59381. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59382. this._postProcesses = new Array();
  59383. }
  59384. this._postProcesses.push(postProcess);
  59385. this._postProcesses[0].autoClear = false;
  59386. };
  59387. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59388. if (!this._postProcesses) {
  59389. return;
  59390. }
  59391. if (dispose) {
  59392. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59393. var postProcess = _a[_i];
  59394. postProcess.dispose();
  59395. }
  59396. }
  59397. this._postProcesses = [];
  59398. };
  59399. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59400. if (!this._postProcesses) {
  59401. return;
  59402. }
  59403. var index = this._postProcesses.indexOf(postProcess);
  59404. if (index === -1) {
  59405. return;
  59406. }
  59407. this._postProcesses.splice(index, 1);
  59408. if (this._postProcesses.length > 0) {
  59409. this._postProcesses[0].autoClear = false;
  59410. }
  59411. };
  59412. RenderTargetTexture.prototype._shouldRender = function () {
  59413. if (this._currentRefreshId === -1) {
  59414. this._currentRefreshId = 1;
  59415. return true;
  59416. }
  59417. if (this.refreshRate === this._currentRefreshId) {
  59418. this._currentRefreshId = 1;
  59419. return true;
  59420. }
  59421. this._currentRefreshId++;
  59422. return false;
  59423. };
  59424. RenderTargetTexture.prototype.getRenderSize = function () {
  59425. if (this._size.width) {
  59426. return this._size.width;
  59427. }
  59428. return this._size;
  59429. };
  59430. RenderTargetTexture.prototype.getRenderWidth = function () {
  59431. if (this._size.width) {
  59432. return this._size.width;
  59433. }
  59434. return this._size;
  59435. };
  59436. RenderTargetTexture.prototype.getRenderHeight = function () {
  59437. if (this._size.width) {
  59438. return this._size.height;
  59439. }
  59440. return this._size;
  59441. };
  59442. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59443. get: function () {
  59444. return true;
  59445. },
  59446. enumerable: true,
  59447. configurable: true
  59448. });
  59449. RenderTargetTexture.prototype.scale = function (ratio) {
  59450. var newSize = this.getRenderSize() * ratio;
  59451. this.resize(newSize);
  59452. };
  59453. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59454. if (this.isCube) {
  59455. return this._textureMatrix;
  59456. }
  59457. return _super.prototype.getReflectionTextureMatrix.call(this);
  59458. };
  59459. RenderTargetTexture.prototype.resize = function (size) {
  59460. this.releaseInternalTexture();
  59461. var scene = this.getScene();
  59462. if (!scene) {
  59463. return;
  59464. }
  59465. this._processSizeParameter(size);
  59466. if (this.isCube) {
  59467. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59468. }
  59469. else {
  59470. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59471. }
  59472. };
  59473. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59474. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59475. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59476. var scene = this.getScene();
  59477. if (!scene) {
  59478. return;
  59479. }
  59480. var engine = scene.getEngine();
  59481. if (this.useCameraPostProcesses !== undefined) {
  59482. useCameraPostProcess = this.useCameraPostProcesses;
  59483. }
  59484. if (this._waitingRenderList) {
  59485. this.renderList = [];
  59486. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59487. var id = this._waitingRenderList[index];
  59488. var mesh_1 = scene.getMeshByID(id);
  59489. if (mesh_1) {
  59490. this.renderList.push(mesh_1);
  59491. }
  59492. }
  59493. delete this._waitingRenderList;
  59494. }
  59495. // Is predicate defined?
  59496. if (this.renderListPredicate) {
  59497. if (this.renderList) {
  59498. this.renderList.splice(0); // Clear previous renderList
  59499. }
  59500. else {
  59501. this.renderList = [];
  59502. }
  59503. var scene = this.getScene();
  59504. if (!scene) {
  59505. return;
  59506. }
  59507. var sceneMeshes = scene.meshes;
  59508. for (var index = 0; index < sceneMeshes.length; index++) {
  59509. var mesh = sceneMeshes[index];
  59510. if (this.renderListPredicate(mesh)) {
  59511. this.renderList.push(mesh);
  59512. }
  59513. }
  59514. }
  59515. this.onBeforeBindObservable.notifyObservers(this);
  59516. // Set custom projection.
  59517. // Needs to be before binding to prevent changing the aspect ratio.
  59518. var camera;
  59519. if (this.activeCamera) {
  59520. camera = this.activeCamera;
  59521. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59522. if (this.activeCamera !== scene.activeCamera) {
  59523. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59524. }
  59525. }
  59526. else {
  59527. camera = scene.activeCamera;
  59528. if (camera) {
  59529. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59530. }
  59531. }
  59532. // Prepare renderingManager
  59533. this._renderingManager.reset();
  59534. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59535. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59536. var sceneRenderId = scene.getRenderId();
  59537. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59538. var mesh = currentRenderList[meshIndex];
  59539. if (mesh) {
  59540. if (!mesh.isReady(this.refreshRate === 0)) {
  59541. this.resetRefreshCounter();
  59542. continue;
  59543. }
  59544. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59545. var isMasked = void 0;
  59546. if (!this.renderList && camera) {
  59547. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59548. }
  59549. else {
  59550. isMasked = false;
  59551. }
  59552. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59553. mesh._activate(sceneRenderId);
  59554. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59555. var subMesh = mesh.subMeshes[subIndex];
  59556. scene._activeIndices.addCount(subMesh.indexCount, false);
  59557. this._renderingManager.dispatch(subMesh, mesh);
  59558. }
  59559. }
  59560. }
  59561. }
  59562. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59563. var particleSystem = scene.particleSystems[particleIndex];
  59564. var emitter = particleSystem.emitter;
  59565. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59566. continue;
  59567. }
  59568. if (currentRenderList.indexOf(emitter) >= 0) {
  59569. this._renderingManager.dispatchParticles(particleSystem);
  59570. }
  59571. }
  59572. if (this.isCube) {
  59573. for (var face = 0; face < 6; face++) {
  59574. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59575. scene.incrementRenderId();
  59576. scene.resetCachedMaterial();
  59577. }
  59578. }
  59579. else {
  59580. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59581. }
  59582. this.onAfterUnbindObservable.notifyObservers(this);
  59583. if (scene.activeCamera) {
  59584. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59585. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59586. }
  59587. engine.setViewport(scene.activeCamera.viewport);
  59588. }
  59589. scene.resetCachedMaterial();
  59590. };
  59591. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59592. var minimum = 128;
  59593. var x = renderDimension * scale;
  59594. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59595. // Ensure we don't exceed the render dimension (while staying POT)
  59596. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59597. };
  59598. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59599. var _this = this;
  59600. if (!this._texture) {
  59601. return;
  59602. }
  59603. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59604. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59605. });
  59606. };
  59607. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59608. var scene = this.getScene();
  59609. if (!scene) {
  59610. return;
  59611. }
  59612. var engine = scene.getEngine();
  59613. if (!this._texture) {
  59614. return;
  59615. }
  59616. // Bind
  59617. if (this._postProcessManager) {
  59618. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59619. }
  59620. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59621. if (this._texture) {
  59622. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59623. }
  59624. }
  59625. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59626. // Clear
  59627. if (this.onClearObservable.hasObservers()) {
  59628. this.onClearObservable.notifyObservers(engine);
  59629. }
  59630. else {
  59631. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59632. }
  59633. if (!this._doNotChangeAspectRatio) {
  59634. scene.updateTransformMatrix(true);
  59635. }
  59636. // Render
  59637. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59638. if (this._postProcessManager) {
  59639. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59640. }
  59641. else if (useCameraPostProcess) {
  59642. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59643. }
  59644. if (!this._doNotChangeAspectRatio) {
  59645. scene.updateTransformMatrix(true);
  59646. }
  59647. // Dump ?
  59648. if (dumpForDebug) {
  59649. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59650. }
  59651. // Unbind
  59652. if (!this.isCube || faceIndex === 5) {
  59653. if (this.isCube) {
  59654. if (faceIndex === 5) {
  59655. engine.generateMipMapsForCubemap(this._texture);
  59656. }
  59657. }
  59658. this.unbindFrameBuffer(engine, faceIndex);
  59659. }
  59660. else {
  59661. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59662. }
  59663. };
  59664. /**
  59665. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59666. * This allowed control for front to back rendering or reversly depending of the special needs.
  59667. *
  59668. * @param renderingGroupId The rendering group id corresponding to its index
  59669. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59670. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59671. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59672. */
  59673. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59674. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59675. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59676. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59677. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59678. };
  59679. /**
  59680. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59681. *
  59682. * @param renderingGroupId The rendering group id corresponding to its index
  59683. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59684. */
  59685. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59686. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59687. };
  59688. RenderTargetTexture.prototype.clone = function () {
  59689. var textureSize = this.getSize();
  59690. 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);
  59691. // Base texture
  59692. newTexture.hasAlpha = this.hasAlpha;
  59693. newTexture.level = this.level;
  59694. // RenderTarget Texture
  59695. newTexture.coordinatesMode = this.coordinatesMode;
  59696. if (this.renderList) {
  59697. newTexture.renderList = this.renderList.slice(0);
  59698. }
  59699. return newTexture;
  59700. };
  59701. RenderTargetTexture.prototype.serialize = function () {
  59702. if (!this.name) {
  59703. return null;
  59704. }
  59705. var serializationObject = _super.prototype.serialize.call(this);
  59706. serializationObject.renderTargetSize = this.getRenderSize();
  59707. serializationObject.renderList = [];
  59708. if (this.renderList) {
  59709. for (var index = 0; index < this.renderList.length; index++) {
  59710. serializationObject.renderList.push(this.renderList[index].id);
  59711. }
  59712. }
  59713. return serializationObject;
  59714. };
  59715. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59716. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59717. var objBuffer = this.getInternalTexture();
  59718. var scene = this.getScene();
  59719. if (objBuffer && scene) {
  59720. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59721. }
  59722. };
  59723. RenderTargetTexture.prototype.dispose = function () {
  59724. if (this._postProcessManager) {
  59725. this._postProcessManager.dispose();
  59726. this._postProcessManager = null;
  59727. }
  59728. this.clearPostProcesses(true);
  59729. if (this._resizeObserver) {
  59730. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59731. this._resizeObserver = null;
  59732. }
  59733. this.renderList = null;
  59734. // Remove from custom render targets
  59735. var scene = this.getScene();
  59736. if (!scene) {
  59737. return;
  59738. }
  59739. var index = scene.customRenderTargets.indexOf(this);
  59740. if (index >= 0) {
  59741. scene.customRenderTargets.splice(index, 1);
  59742. }
  59743. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59744. var camera = _a[_i];
  59745. index = camera.customRenderTargets.indexOf(this);
  59746. if (index >= 0) {
  59747. camera.customRenderTargets.splice(index, 1);
  59748. }
  59749. }
  59750. _super.prototype.dispose.call(this);
  59751. };
  59752. RenderTargetTexture.prototype._rebuild = function () {
  59753. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59754. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59755. }
  59756. if (this._postProcessManager) {
  59757. this._postProcessManager._rebuild();
  59758. }
  59759. };
  59760. /**
  59761. * Clear the info related to rendering groups preventing retention point in material dispose.
  59762. */
  59763. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59764. if (this._renderingManager) {
  59765. this._renderingManager.freeRenderingGroups();
  59766. }
  59767. };
  59768. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59769. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59770. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59771. return RenderTargetTexture;
  59772. }(BABYLON.Texture));
  59773. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59774. })(BABYLON || (BABYLON = {}));
  59775. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59776. "use strict";
  59777. var BABYLON;
  59778. (function (BABYLON) {
  59779. ;
  59780. var MultiRenderTarget = /** @class */ (function (_super) {
  59781. __extends(MultiRenderTarget, _super);
  59782. function MultiRenderTarget(name, size, count, scene, options) {
  59783. var _this = this;
  59784. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59785. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59786. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59787. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59788. _this._engine = scene.getEngine();
  59789. if (!_this.isSupported) {
  59790. _this.dispose();
  59791. return;
  59792. }
  59793. var types = [];
  59794. var samplingModes = [];
  59795. for (var i = 0; i < count; i++) {
  59796. if (options && options.types && options.types[i] !== undefined) {
  59797. types.push(options.types[i]);
  59798. }
  59799. else {
  59800. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59801. }
  59802. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59803. samplingModes.push(options.samplingModes[i]);
  59804. }
  59805. else {
  59806. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59807. }
  59808. }
  59809. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59810. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59811. _this._size = size;
  59812. _this._multiRenderTargetOptions = {
  59813. samplingModes: samplingModes,
  59814. generateMipMaps: generateMipMaps,
  59815. generateDepthBuffer: generateDepthBuffer,
  59816. generateStencilBuffer: generateStencilBuffer,
  59817. generateDepthTexture: generateDepthTexture,
  59818. types: types,
  59819. textureCount: count
  59820. };
  59821. _this._createInternalTextures();
  59822. _this._createTextures();
  59823. return _this;
  59824. }
  59825. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59826. get: function () {
  59827. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59828. },
  59829. enumerable: true,
  59830. configurable: true
  59831. });
  59832. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59833. get: function () {
  59834. return this._textures;
  59835. },
  59836. enumerable: true,
  59837. configurable: true
  59838. });
  59839. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59840. get: function () {
  59841. return this._textures[this._textures.length - 1];
  59842. },
  59843. enumerable: true,
  59844. configurable: true
  59845. });
  59846. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59847. set: function (wrap) {
  59848. if (this._textures) {
  59849. for (var i = 0; i < this._textures.length; i++) {
  59850. this._textures[i].wrapU = wrap;
  59851. }
  59852. }
  59853. },
  59854. enumerable: true,
  59855. configurable: true
  59856. });
  59857. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59858. set: function (wrap) {
  59859. if (this._textures) {
  59860. for (var i = 0; i < this._textures.length; i++) {
  59861. this._textures[i].wrapV = wrap;
  59862. }
  59863. }
  59864. },
  59865. enumerable: true,
  59866. configurable: true
  59867. });
  59868. MultiRenderTarget.prototype._rebuild = function () {
  59869. this.releaseInternalTextures();
  59870. this._createInternalTextures();
  59871. for (var i = 0; i < this._internalTextures.length; i++) {
  59872. var texture = this._textures[i];
  59873. texture._texture = this._internalTextures[i];
  59874. }
  59875. // Keeps references to frame buffer and stencil/depth buffer
  59876. this._texture = this._internalTextures[0];
  59877. };
  59878. MultiRenderTarget.prototype._createInternalTextures = function () {
  59879. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59880. };
  59881. MultiRenderTarget.prototype._createTextures = function () {
  59882. this._textures = [];
  59883. for (var i = 0; i < this._internalTextures.length; i++) {
  59884. var texture = new BABYLON.Texture(null, this.getScene());
  59885. texture._texture = this._internalTextures[i];
  59886. this._textures.push(texture);
  59887. }
  59888. // Keeps references to frame buffer and stencil/depth buffer
  59889. this._texture = this._internalTextures[0];
  59890. };
  59891. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59892. get: function () {
  59893. return this._samples;
  59894. },
  59895. set: function (value) {
  59896. if (this._samples === value) {
  59897. return;
  59898. }
  59899. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59900. },
  59901. enumerable: true,
  59902. configurable: true
  59903. });
  59904. MultiRenderTarget.prototype.resize = function (size) {
  59905. this.releaseInternalTextures();
  59906. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59907. this._createInternalTextures();
  59908. };
  59909. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59910. var _this = this;
  59911. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59912. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59913. });
  59914. };
  59915. MultiRenderTarget.prototype.dispose = function () {
  59916. this.releaseInternalTextures();
  59917. _super.prototype.dispose.call(this);
  59918. };
  59919. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59920. if (!this._internalTextures) {
  59921. return;
  59922. }
  59923. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59924. if (this._internalTextures[i] !== undefined) {
  59925. this._internalTextures[i].dispose();
  59926. this._internalTextures.splice(i, 1);
  59927. }
  59928. }
  59929. };
  59930. return MultiRenderTarget;
  59931. }(BABYLON.RenderTargetTexture));
  59932. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59933. })(BABYLON || (BABYLON = {}));
  59934. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59935. "use strict";
  59936. var BABYLON;
  59937. (function (BABYLON) {
  59938. var MirrorTexture = /** @class */ (function (_super) {
  59939. __extends(MirrorTexture, _super);
  59940. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59941. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59942. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59943. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59944. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59945. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59946. _this._transformMatrix = BABYLON.Matrix.Zero();
  59947. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59948. _this._adaptiveBlurKernel = 0;
  59949. _this._blurKernelX = 0;
  59950. _this._blurKernelY = 0;
  59951. _this._blurRatio = 1.0;
  59952. _this.ignoreCameraViewport = true;
  59953. _this.onBeforeRenderObservable.add(function () {
  59954. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59955. _this._savedViewMatrix = scene.getViewMatrix();
  59956. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59957. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59958. scene.clipPlane = _this.mirrorPlane;
  59959. scene.getEngine().cullBackFaces = false;
  59960. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59961. });
  59962. _this.onAfterRenderObservable.add(function () {
  59963. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59964. scene.getEngine().cullBackFaces = true;
  59965. scene._mirroredCameraPosition = null;
  59966. delete scene.clipPlane;
  59967. });
  59968. return _this;
  59969. }
  59970. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59971. get: function () {
  59972. return this._blurRatio;
  59973. },
  59974. set: function (value) {
  59975. if (this._blurRatio === value) {
  59976. return;
  59977. }
  59978. this._blurRatio = value;
  59979. this._preparePostProcesses();
  59980. },
  59981. enumerable: true,
  59982. configurable: true
  59983. });
  59984. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59985. set: function (value) {
  59986. this._adaptiveBlurKernel = value;
  59987. this._autoComputeBlurKernel();
  59988. },
  59989. enumerable: true,
  59990. configurable: true
  59991. });
  59992. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59993. set: function (value) {
  59994. this.blurKernelX = value;
  59995. this.blurKernelY = value;
  59996. },
  59997. enumerable: true,
  59998. configurable: true
  59999. });
  60000. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  60001. get: function () {
  60002. return this._blurKernelX;
  60003. },
  60004. set: function (value) {
  60005. if (this._blurKernelX === value) {
  60006. return;
  60007. }
  60008. this._blurKernelX = value;
  60009. this._preparePostProcesses();
  60010. },
  60011. enumerable: true,
  60012. configurable: true
  60013. });
  60014. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  60015. get: function () {
  60016. return this._blurKernelY;
  60017. },
  60018. set: function (value) {
  60019. if (this._blurKernelY === value) {
  60020. return;
  60021. }
  60022. this._blurKernelY = value;
  60023. this._preparePostProcesses();
  60024. },
  60025. enumerable: true,
  60026. configurable: true
  60027. });
  60028. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  60029. var engine = this.getScene().getEngine();
  60030. var dw = this.getRenderWidth() / engine.getRenderWidth();
  60031. var dh = this.getRenderHeight() / engine.getRenderHeight();
  60032. this.blurKernelX = this._adaptiveBlurKernel * dw;
  60033. this.blurKernelY = this._adaptiveBlurKernel * dh;
  60034. };
  60035. MirrorTexture.prototype._onRatioRescale = function () {
  60036. if (this._sizeRatio) {
  60037. this.resize(this._initialSizeParameter);
  60038. if (!this._adaptiveBlurKernel) {
  60039. this._preparePostProcesses();
  60040. }
  60041. }
  60042. if (this._adaptiveBlurKernel) {
  60043. this._autoComputeBlurKernel();
  60044. }
  60045. };
  60046. MirrorTexture.prototype._preparePostProcesses = function () {
  60047. this.clearPostProcesses(true);
  60048. if (this._blurKernelX && this._blurKernelY) {
  60049. var engine = this.getScene().getEngine();
  60050. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60051. 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);
  60052. this._blurX.autoClear = false;
  60053. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  60054. this._blurX.inputTexture = this._texture;
  60055. }
  60056. else {
  60057. this._blurX.alwaysForcePOT = true;
  60058. }
  60059. 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);
  60060. this._blurY.autoClear = false;
  60061. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  60062. this.addPostProcess(this._blurX);
  60063. this.addPostProcess(this._blurY);
  60064. }
  60065. else {
  60066. if (this._blurY) {
  60067. this.removePostProcess(this._blurY);
  60068. this._blurY.dispose();
  60069. this._blurY = null;
  60070. }
  60071. if (this._blurX) {
  60072. this.removePostProcess(this._blurX);
  60073. this._blurX.dispose();
  60074. this._blurX = null;
  60075. }
  60076. }
  60077. };
  60078. MirrorTexture.prototype.clone = function () {
  60079. var scene = this.getScene();
  60080. if (!scene) {
  60081. return this;
  60082. }
  60083. var textureSize = this.getSize();
  60084. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  60085. // Base texture
  60086. newTexture.hasAlpha = this.hasAlpha;
  60087. newTexture.level = this.level;
  60088. // Mirror Texture
  60089. newTexture.mirrorPlane = this.mirrorPlane.clone();
  60090. if (this.renderList) {
  60091. newTexture.renderList = this.renderList.slice(0);
  60092. }
  60093. return newTexture;
  60094. };
  60095. MirrorTexture.prototype.serialize = function () {
  60096. if (!this.name) {
  60097. return null;
  60098. }
  60099. var serializationObject = _super.prototype.serialize.call(this);
  60100. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  60101. return serializationObject;
  60102. };
  60103. return MirrorTexture;
  60104. }(BABYLON.RenderTargetTexture));
  60105. BABYLON.MirrorTexture = MirrorTexture;
  60106. })(BABYLON || (BABYLON = {}));
  60107. //# sourceMappingURL=babylon.mirrorTexture.js.map
  60108. "use strict";
  60109. var BABYLON;
  60110. (function (BABYLON) {
  60111. /**
  60112. * Creates a refraction texture used by refraction channel of the standard material.
  60113. * @param name the texture name
  60114. * @param size size of the underlying texture
  60115. * @param scene root scene
  60116. */
  60117. var RefractionTexture = /** @class */ (function (_super) {
  60118. __extends(RefractionTexture, _super);
  60119. function RefractionTexture(name, size, scene, generateMipMaps) {
  60120. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  60121. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  60122. _this.depth = 2.0;
  60123. _this.onBeforeRenderObservable.add(function () {
  60124. scene.clipPlane = _this.refractionPlane;
  60125. });
  60126. _this.onAfterRenderObservable.add(function () {
  60127. delete scene.clipPlane;
  60128. });
  60129. return _this;
  60130. }
  60131. RefractionTexture.prototype.clone = function () {
  60132. var scene = this.getScene();
  60133. if (!scene) {
  60134. return this;
  60135. }
  60136. var textureSize = this.getSize();
  60137. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  60138. // Base texture
  60139. newTexture.hasAlpha = this.hasAlpha;
  60140. newTexture.level = this.level;
  60141. // Refraction Texture
  60142. newTexture.refractionPlane = this.refractionPlane.clone();
  60143. if (this.renderList) {
  60144. newTexture.renderList = this.renderList.slice(0);
  60145. }
  60146. newTexture.depth = this.depth;
  60147. return newTexture;
  60148. };
  60149. RefractionTexture.prototype.serialize = function () {
  60150. if (!this.name) {
  60151. return null;
  60152. }
  60153. var serializationObject = _super.prototype.serialize.call(this);
  60154. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  60155. serializationObject.depth = this.depth;
  60156. return serializationObject;
  60157. };
  60158. return RefractionTexture;
  60159. }(BABYLON.RenderTargetTexture));
  60160. BABYLON.RefractionTexture = RefractionTexture;
  60161. })(BABYLON || (BABYLON = {}));
  60162. //# sourceMappingURL=babylon.refractionTexture.js.map
  60163. "use strict";
  60164. var BABYLON;
  60165. (function (BABYLON) {
  60166. /**
  60167. * A class extending {BABYLON.Texture} allowing drawing on a texture
  60168. * @see http://doc.babylonjs.com/how_to/dynamictexture
  60169. */
  60170. var DynamicTexture = /** @class */ (function (_super) {
  60171. __extends(DynamicTexture, _super);
  60172. /**
  60173. * Creates a {BABYLON.DynamicTexture}
  60174. * @param name defines the name of the texture
  60175. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  60176. * @param scene defines the scene where you want the texture
  60177. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  60178. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  60179. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  60180. */
  60181. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  60182. if (scene === void 0) { scene = null; }
  60183. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60184. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  60185. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  60186. _this.name = name;
  60187. _this._engine = _this.getScene().getEngine();
  60188. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60189. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60190. _this._generateMipMaps = generateMipMaps;
  60191. if (options.getContext) {
  60192. _this._canvas = options;
  60193. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60194. }
  60195. else {
  60196. _this._canvas = document.createElement("canvas");
  60197. if (options.width) {
  60198. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60199. }
  60200. else {
  60201. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  60202. }
  60203. }
  60204. var textureSize = _this.getSize();
  60205. _this._canvas.width = textureSize.width;
  60206. _this._canvas.height = textureSize.height;
  60207. _this._context = _this._canvas.getContext("2d");
  60208. return _this;
  60209. }
  60210. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  60211. /**
  60212. * Gets the current state of canRescale
  60213. */
  60214. get: function () {
  60215. return true;
  60216. },
  60217. enumerable: true,
  60218. configurable: true
  60219. });
  60220. DynamicTexture.prototype._recreate = function (textureSize) {
  60221. this._canvas.width = textureSize.width;
  60222. this._canvas.height = textureSize.height;
  60223. this.releaseInternalTexture();
  60224. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  60225. };
  60226. /**
  60227. * Scales the texture
  60228. * @param ratio the scale factor to apply to both width and height
  60229. */
  60230. DynamicTexture.prototype.scale = function (ratio) {
  60231. var textureSize = this.getSize();
  60232. textureSize.width *= ratio;
  60233. textureSize.height *= ratio;
  60234. this._recreate(textureSize);
  60235. };
  60236. /**
  60237. * Resizes the texture
  60238. * @param width the new width
  60239. * @param height the new height
  60240. */
  60241. DynamicTexture.prototype.scaleTo = function (width, height) {
  60242. var textureSize = this.getSize();
  60243. textureSize.width = width;
  60244. textureSize.height = height;
  60245. this._recreate(textureSize);
  60246. };
  60247. /**
  60248. * Gets the context of the canvas used by the texture
  60249. * @returns the canvas context of the dynamic texture
  60250. */
  60251. DynamicTexture.prototype.getContext = function () {
  60252. return this._context;
  60253. };
  60254. /**
  60255. * Clears the texture
  60256. */
  60257. DynamicTexture.prototype.clear = function () {
  60258. var size = this.getSize();
  60259. this._context.fillRect(0, 0, size.width, size.height);
  60260. };
  60261. /**
  60262. * Updates the texture
  60263. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60264. */
  60265. DynamicTexture.prototype.update = function (invertY) {
  60266. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60267. };
  60268. /**
  60269. * Draws text onto the texture
  60270. * @param text defines the text to be drawn
  60271. * @param x defines the placement of the text from the left
  60272. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  60273. * @param font defines the font to be used with font-style, font-size, font-name
  60274. * @param color defines the color used for the text
  60275. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  60276. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60277. * @param update defines whether texture is immediately update (default is true)
  60278. */
  60279. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60280. if (update === void 0) { update = true; }
  60281. var size = this.getSize();
  60282. if (clearColor) {
  60283. this._context.fillStyle = clearColor;
  60284. this._context.fillRect(0, 0, size.width, size.height);
  60285. }
  60286. this._context.font = font;
  60287. if (x === null || x === undefined) {
  60288. var textSize = this._context.measureText(text);
  60289. x = (size.width - textSize.width) / 2;
  60290. }
  60291. if (y === null || y === undefined) {
  60292. var fontSize = parseInt((font.replace(/\D/g, '')));
  60293. ;
  60294. y = (size.height / 2) + (fontSize / 3.65);
  60295. }
  60296. this._context.fillStyle = color;
  60297. this._context.fillText(text, x, y);
  60298. if (update) {
  60299. this.update(invertY);
  60300. }
  60301. };
  60302. /**
  60303. * Clones the texture
  60304. * @returns the clone of the texture.
  60305. */
  60306. DynamicTexture.prototype.clone = function () {
  60307. var scene = this.getScene();
  60308. if (!scene) {
  60309. return this;
  60310. }
  60311. var textureSize = this.getSize();
  60312. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60313. // Base texture
  60314. newTexture.hasAlpha = this.hasAlpha;
  60315. newTexture.level = this.level;
  60316. // Dynamic Texture
  60317. newTexture.wrapU = this.wrapU;
  60318. newTexture.wrapV = this.wrapV;
  60319. return newTexture;
  60320. };
  60321. /** @ignore */
  60322. DynamicTexture.prototype._rebuild = function () {
  60323. this.update();
  60324. };
  60325. return DynamicTexture;
  60326. }(BABYLON.Texture));
  60327. BABYLON.DynamicTexture = DynamicTexture;
  60328. })(BABYLON || (BABYLON = {}));
  60329. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60330. "use strict";
  60331. var BABYLON;
  60332. (function (BABYLON) {
  60333. var VideoTexture = /** @class */ (function (_super) {
  60334. __extends(VideoTexture, _super);
  60335. /**
  60336. * Creates a video texture.
  60337. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60338. * @param {string | null} name optional name, will detect from video source, if not defined
  60339. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60340. * @param {BABYLON.Scene} scene is obviously the current scene.
  60341. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60342. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60343. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60344. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60345. */
  60346. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60347. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60348. if (invertY === void 0) { invertY = false; }
  60349. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60350. if (settings === void 0) { settings = {
  60351. autoPlay: true,
  60352. loop: true,
  60353. autoUpdateTexture: true,
  60354. }; }
  60355. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60356. _this._createInternalTexture = function () {
  60357. if (_this._texture != null) {
  60358. return;
  60359. }
  60360. if (!_this._engine.needPOTTextures ||
  60361. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60362. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60363. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60364. }
  60365. else {
  60366. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60367. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60368. _this._generateMipMaps = false;
  60369. }
  60370. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60371. _this._texture.isReady = true;
  60372. _this._updateInternalTexture();
  60373. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60374. _this.onLoadObservable.notifyObservers(_this);
  60375. }
  60376. };
  60377. _this.reset = function () {
  60378. if (_this._texture == null) {
  60379. return;
  60380. }
  60381. _this._texture.dispose();
  60382. _this._texture = null;
  60383. };
  60384. _this._updateInternalTexture = function (e) {
  60385. if (_this._texture == null || !_this._texture.isReady) {
  60386. return;
  60387. }
  60388. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60389. return;
  60390. }
  60391. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60392. };
  60393. _this._engine = _this.getScene().getEngine();
  60394. _this._generateMipMaps = generateMipMaps;
  60395. _this._samplingMode = samplingMode;
  60396. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60397. _this.name = name || _this._getName(src);
  60398. _this.video = _this._getVideo(src);
  60399. if (settings.autoPlay !== undefined) {
  60400. _this.video.autoplay = settings.autoPlay;
  60401. }
  60402. if (settings.loop !== undefined) {
  60403. _this.video.loop = settings.loop;
  60404. }
  60405. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60406. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60407. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60408. _this.video.addEventListener("emptied", _this.reset);
  60409. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60410. _this._createInternalTexture();
  60411. }
  60412. return _this;
  60413. }
  60414. VideoTexture.prototype._getName = function (src) {
  60415. if (src instanceof HTMLVideoElement) {
  60416. return src.currentSrc;
  60417. }
  60418. if (typeof src === "object") {
  60419. return src.toString();
  60420. }
  60421. return src;
  60422. };
  60423. ;
  60424. VideoTexture.prototype._getVideo = function (src) {
  60425. if (src instanceof HTMLVideoElement) {
  60426. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60427. return src;
  60428. }
  60429. var video = document.createElement("video");
  60430. if (typeof src === "string") {
  60431. BABYLON.Tools.SetCorsBehavior(src, video);
  60432. video.src = src;
  60433. }
  60434. else {
  60435. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60436. src.forEach(function (url) {
  60437. var source = document.createElement("source");
  60438. source.src = url;
  60439. video.appendChild(source);
  60440. });
  60441. }
  60442. return video;
  60443. };
  60444. ;
  60445. /**
  60446. * Internal method to initiate `update`.
  60447. */
  60448. VideoTexture.prototype._rebuild = function () {
  60449. this.update();
  60450. };
  60451. /**
  60452. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60453. */
  60454. VideoTexture.prototype.update = function () {
  60455. if (!this.autoUpdateTexture) {
  60456. // Expecting user to call `updateTexture` manually
  60457. return;
  60458. }
  60459. this.updateTexture(true);
  60460. };
  60461. /**
  60462. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60463. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60464. */
  60465. VideoTexture.prototype.updateTexture = function (isVisible) {
  60466. if (!isVisible) {
  60467. return;
  60468. }
  60469. if (this.video.paused) {
  60470. return;
  60471. }
  60472. this._updateInternalTexture();
  60473. };
  60474. /**
  60475. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60476. * @param url New url.
  60477. */
  60478. VideoTexture.prototype.updateURL = function (url) {
  60479. this.video.src = url;
  60480. };
  60481. VideoTexture.prototype.dispose = function () {
  60482. _super.prototype.dispose.call(this);
  60483. this.video.removeEventListener("canplay", this._createInternalTexture);
  60484. this.video.removeEventListener("paused", this._updateInternalTexture);
  60485. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60486. this.video.removeEventListener("emptied", this.reset);
  60487. this.video.pause();
  60488. };
  60489. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60490. var video = document.createElement("video");
  60491. var constraintsDeviceId;
  60492. if (constraints && constraints.deviceId) {
  60493. constraintsDeviceId = {
  60494. exact: constraints.deviceId,
  60495. };
  60496. }
  60497. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60498. if (navigator.mediaDevices) {
  60499. navigator.mediaDevices.getUserMedia({ video: constraints })
  60500. .then(function (stream) {
  60501. if (video.mozSrcObject !== undefined) {
  60502. // hack for Firefox < 19
  60503. video.mozSrcObject = stream;
  60504. }
  60505. else {
  60506. video.srcObject = stream;
  60507. }
  60508. var onPlaying = function () {
  60509. if (onReady) {
  60510. onReady(new VideoTexture("video", video, scene, true, true));
  60511. }
  60512. video.removeEventListener("playing", onPlaying);
  60513. };
  60514. video.addEventListener("playing", onPlaying);
  60515. video.play();
  60516. })
  60517. .catch(function (err) {
  60518. BABYLON.Tools.Error(err.name);
  60519. });
  60520. }
  60521. else {
  60522. navigator.getUserMedia =
  60523. navigator.getUserMedia ||
  60524. navigator.webkitGetUserMedia ||
  60525. navigator.mozGetUserMedia ||
  60526. navigator.msGetUserMedia;
  60527. if (navigator.getUserMedia) {
  60528. navigator.getUserMedia({
  60529. video: {
  60530. deviceId: constraintsDeviceId,
  60531. width: {
  60532. min: (constraints && constraints.minWidth) || 256,
  60533. max: (constraints && constraints.maxWidth) || 640,
  60534. },
  60535. height: {
  60536. min: (constraints && constraints.minHeight) || 256,
  60537. max: (constraints && constraints.maxHeight) || 480,
  60538. },
  60539. },
  60540. }, function (stream) {
  60541. if (video.mozSrcObject !== undefined) {
  60542. // hack for Firefox < 19
  60543. video.mozSrcObject = stream;
  60544. }
  60545. else {
  60546. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60547. }
  60548. video.play();
  60549. if (onReady) {
  60550. onReady(new VideoTexture("video", video, scene, true, true));
  60551. }
  60552. }, function (e) {
  60553. BABYLON.Tools.Error(e.name);
  60554. });
  60555. }
  60556. }
  60557. };
  60558. return VideoTexture;
  60559. }(BABYLON.Texture));
  60560. BABYLON.VideoTexture = VideoTexture;
  60561. })(BABYLON || (BABYLON = {}));
  60562. //# sourceMappingURL=babylon.videoTexture.js.map
  60563. "use strict";
  60564. var BABYLON;
  60565. (function (BABYLON) {
  60566. var RawTexture = /** @class */ (function (_super) {
  60567. __extends(RawTexture, _super);
  60568. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60569. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60570. if (invertY === void 0) { invertY = false; }
  60571. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60572. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60573. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60574. _this.format = format;
  60575. _this._engine = scene.getEngine();
  60576. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60577. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60578. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60579. return _this;
  60580. }
  60581. RawTexture.prototype.update = function (data) {
  60582. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60583. };
  60584. // Statics
  60585. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60586. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60587. if (invertY === void 0) { invertY = false; }
  60588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60589. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60590. };
  60591. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60592. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60593. if (invertY === void 0) { invertY = false; }
  60594. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60595. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60596. };
  60597. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60598. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60599. if (invertY === void 0) { invertY = false; }
  60600. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60601. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60602. };
  60603. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60604. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60605. if (invertY === void 0) { invertY = false; }
  60606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60607. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60608. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60609. };
  60610. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60611. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60612. if (invertY === void 0) { invertY = false; }
  60613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60614. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60615. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60616. };
  60617. return RawTexture;
  60618. }(BABYLON.Texture));
  60619. BABYLON.RawTexture = RawTexture;
  60620. })(BABYLON || (BABYLON = {}));
  60621. //# sourceMappingURL=babylon.rawTexture.js.map
  60622. "use strict";
  60623. var BABYLON;
  60624. (function (BABYLON) {
  60625. /**
  60626. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60627. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60628. */
  60629. var PostProcess = /** @class */ (function () {
  60630. /**
  60631. * Creates a new instance of @see PostProcess
  60632. * @param name The name of the PostProcess.
  60633. * @param fragmentUrl The url of the fragment shader to be used.
  60634. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60635. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60636. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60637. * @param camera The camera to apply the render pass to.
  60638. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60639. * @param engine The engine which the post process will be applied. (default: current engine)
  60640. * @param reusable If the post process can be reused on the same frame. (default: false)
  60641. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60642. * @param textureType Type of textures used when performing the post process. (default: 0)
  60643. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60644. * @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
  60645. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60646. */
  60647. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60649. if (defines === void 0) { defines = null; }
  60650. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60651. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60652. if (blockCompilation === void 0) { blockCompilation = false; }
  60653. this.name = name;
  60654. /**
  60655. * Width of the texture to apply the post process on
  60656. */
  60657. this.width = -1;
  60658. /**
  60659. * Height of the texture to apply the post process on
  60660. */
  60661. this.height = -1;
  60662. /**
  60663. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60664. */
  60665. this._outputTexture = null;
  60666. /**
  60667. * If the buffer needs to be cleared before applying the post process. (default: true)
  60668. * Should be set to false if shader will overwrite all previous pixels.
  60669. */
  60670. this.autoClear = true;
  60671. /**
  60672. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60673. */
  60674. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60675. /**
  60676. * Animations to be used for the post processing
  60677. */
  60678. this.animations = new Array();
  60679. /**
  60680. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60681. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60682. */
  60683. this.enablePixelPerfectMode = false;
  60684. /**
  60685. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60686. */
  60687. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60688. /**
  60689. * Force textures to be a power of two (default: false)
  60690. */
  60691. this.alwaysForcePOT = false;
  60692. /**
  60693. * Number of sample textures (default: 1)
  60694. */
  60695. this.samples = 1;
  60696. /**
  60697. * Modify the scale of the post process to be the same as the viewport (default: false)
  60698. */
  60699. this.adaptScaleToCurrentViewport = false;
  60700. this._reusable = false;
  60701. /**
  60702. * Smart array of input and output textures for the post process.
  60703. */
  60704. this._textures = new BABYLON.SmartArray(2);
  60705. /**
  60706. * The index in _textures that corresponds to the output texture.
  60707. */
  60708. this._currentRenderTextureInd = 0;
  60709. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60710. this._texelSize = BABYLON.Vector2.Zero();
  60711. // Events
  60712. /**
  60713. * An event triggered when the postprocess is activated.
  60714. * @type {BABYLON.Observable}
  60715. */
  60716. this.onActivateObservable = new BABYLON.Observable();
  60717. /**
  60718. * An event triggered when the postprocess changes its size.
  60719. * @type {BABYLON.Observable}
  60720. */
  60721. this.onSizeChangedObservable = new BABYLON.Observable();
  60722. /**
  60723. * An event triggered when the postprocess applies its effect.
  60724. * @type {BABYLON.Observable}
  60725. */
  60726. this.onApplyObservable = new BABYLON.Observable();
  60727. /**
  60728. * An event triggered before rendering the postprocess
  60729. * @type {BABYLON.Observable}
  60730. */
  60731. this.onBeforeRenderObservable = new BABYLON.Observable();
  60732. /**
  60733. * An event triggered after rendering the postprocess
  60734. * @type {BABYLON.Observable}
  60735. */
  60736. this.onAfterRenderObservable = new BABYLON.Observable();
  60737. if (camera != null) {
  60738. this._camera = camera;
  60739. this._scene = camera.getScene();
  60740. camera.attachPostProcess(this);
  60741. this._engine = this._scene.getEngine();
  60742. this._scene.postProcesses.push(this);
  60743. }
  60744. else if (engine) {
  60745. this._engine = engine;
  60746. this._engine.postProcesses.push(this);
  60747. }
  60748. this._options = options;
  60749. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60750. this._reusable = reusable || false;
  60751. this._textureType = textureType;
  60752. this._samplers = samplers || [];
  60753. this._samplers.push("textureSampler");
  60754. this._fragmentUrl = fragmentUrl;
  60755. this._vertexUrl = vertexUrl;
  60756. this._parameters = parameters || [];
  60757. this._parameters.push("scale");
  60758. this._indexParameters = indexParameters;
  60759. if (!blockCompilation) {
  60760. this.updateEffect(defines);
  60761. }
  60762. }
  60763. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60764. /**
  60765. * A function that is added to the onActivateObservable
  60766. */
  60767. set: function (callback) {
  60768. if (this._onActivateObserver) {
  60769. this.onActivateObservable.remove(this._onActivateObserver);
  60770. }
  60771. if (callback) {
  60772. this._onActivateObserver = this.onActivateObservable.add(callback);
  60773. }
  60774. },
  60775. enumerable: true,
  60776. configurable: true
  60777. });
  60778. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60779. /**
  60780. * A function that is added to the onSizeChangedObservable
  60781. */
  60782. set: function (callback) {
  60783. if (this._onSizeChangedObserver) {
  60784. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60785. }
  60786. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60787. },
  60788. enumerable: true,
  60789. configurable: true
  60790. });
  60791. Object.defineProperty(PostProcess.prototype, "onApply", {
  60792. /**
  60793. * A function that is added to the onApplyObservable
  60794. */
  60795. set: function (callback) {
  60796. if (this._onApplyObserver) {
  60797. this.onApplyObservable.remove(this._onApplyObserver);
  60798. }
  60799. this._onApplyObserver = this.onApplyObservable.add(callback);
  60800. },
  60801. enumerable: true,
  60802. configurable: true
  60803. });
  60804. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60805. /**
  60806. * A function that is added to the onBeforeRenderObservable
  60807. */
  60808. set: function (callback) {
  60809. if (this._onBeforeRenderObserver) {
  60810. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60811. }
  60812. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60813. },
  60814. enumerable: true,
  60815. configurable: true
  60816. });
  60817. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60818. /**
  60819. * A function that is added to the onAfterRenderObservable
  60820. */
  60821. set: function (callback) {
  60822. if (this._onAfterRenderObserver) {
  60823. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60824. }
  60825. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60826. },
  60827. enumerable: true,
  60828. configurable: true
  60829. });
  60830. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60831. /**
  60832. * 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
  60833. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60834. */
  60835. get: function () {
  60836. return this._textures.data[this._currentRenderTextureInd];
  60837. },
  60838. set: function (value) {
  60839. this._forcedOutputTexture = value;
  60840. },
  60841. enumerable: true,
  60842. configurable: true
  60843. });
  60844. /**
  60845. * Gets the camera which post process is applied to.
  60846. * @returns The camera the post process is applied to.
  60847. */
  60848. PostProcess.prototype.getCamera = function () {
  60849. return this._camera;
  60850. };
  60851. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60852. /**
  60853. * Gets the texel size of the postprocess.
  60854. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60855. */
  60856. get: function () {
  60857. if (this._shareOutputWithPostProcess) {
  60858. return this._shareOutputWithPostProcess.texelSize;
  60859. }
  60860. if (this._forcedOutputTexture) {
  60861. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60862. }
  60863. return this._texelSize;
  60864. },
  60865. enumerable: true,
  60866. configurable: true
  60867. });
  60868. /**
  60869. * Gets the engine which this post process belongs to.
  60870. * @returns The engine the post process was enabled with.
  60871. */
  60872. PostProcess.prototype.getEngine = function () {
  60873. return this._engine;
  60874. };
  60875. /**
  60876. * The effect that is created when initializing the post process.
  60877. * @returns The created effect corrisponding the the postprocess.
  60878. */
  60879. PostProcess.prototype.getEffect = function () {
  60880. return this._effect;
  60881. };
  60882. /**
  60883. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60884. * @param postProcess The post process to share the output with.
  60885. * @returns This post process.
  60886. */
  60887. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60888. this._disposeTextures();
  60889. this._shareOutputWithPostProcess = postProcess;
  60890. return this;
  60891. };
  60892. /**
  60893. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60894. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60895. */
  60896. PostProcess.prototype.useOwnOutput = function () {
  60897. if (this._textures.length == 0) {
  60898. this._textures = new BABYLON.SmartArray(2);
  60899. }
  60900. this._shareOutputWithPostProcess = null;
  60901. };
  60902. /**
  60903. * Updates the effect with the current post process compile time values and recompiles the shader.
  60904. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60905. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60906. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60907. * @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
  60908. * @param onCompiled Called when the shader has been compiled.
  60909. * @param onError Called if there is an error when compiling a shader.
  60910. */
  60911. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60912. if (defines === void 0) { defines = null; }
  60913. if (uniforms === void 0) { uniforms = null; }
  60914. if (samplers === void 0) { samplers = null; }
  60915. 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);
  60916. };
  60917. /**
  60918. * The post process is reusable if it can be used multiple times within one frame.
  60919. * @returns If the post process is reusable
  60920. */
  60921. PostProcess.prototype.isReusable = function () {
  60922. return this._reusable;
  60923. };
  60924. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60925. PostProcess.prototype.markTextureDirty = function () {
  60926. this.width = -1;
  60927. };
  60928. /**
  60929. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60930. * 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.
  60931. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60932. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60933. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60934. * @returns The target texture that was bound to be written to.
  60935. */
  60936. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60937. var _this = this;
  60938. if (sourceTexture === void 0) { sourceTexture = null; }
  60939. camera = camera || this._camera;
  60940. var scene = camera.getScene();
  60941. var engine = scene.getEngine();
  60942. var maxSize = engine.getCaps().maxTextureSize;
  60943. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60944. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60945. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  60946. var webVRCamera = camera.parent;
  60947. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60948. requiredWidth /= 2;
  60949. }
  60950. var desiredWidth = (this._options.width || requiredWidth);
  60951. var desiredHeight = this._options.height || requiredHeight;
  60952. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60953. if (this.adaptScaleToCurrentViewport) {
  60954. var currentViewport = engine.currentViewport;
  60955. if (currentViewport) {
  60956. desiredWidth *= currentViewport.width;
  60957. desiredHeight *= currentViewport.height;
  60958. }
  60959. }
  60960. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60961. if (!this._options.width) {
  60962. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60963. }
  60964. if (!this._options.height) {
  60965. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60966. }
  60967. }
  60968. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60969. if (this._textures.length > 0) {
  60970. for (var i = 0; i < this._textures.length; i++) {
  60971. this._engine._releaseTexture(this._textures.data[i]);
  60972. }
  60973. this._textures.reset();
  60974. }
  60975. this.width = desiredWidth;
  60976. this.height = desiredHeight;
  60977. var textureSize = { width: this.width, height: this.height };
  60978. var textureOptions = {
  60979. generateMipMaps: false,
  60980. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60981. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60982. samplingMode: this.renderTargetSamplingMode,
  60983. type: this._textureType
  60984. };
  60985. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60986. if (this._reusable) {
  60987. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60988. }
  60989. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60990. this.onSizeChangedObservable.notifyObservers(this);
  60991. }
  60992. this._textures.forEach(function (texture) {
  60993. if (texture.samples !== _this.samples) {
  60994. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60995. }
  60996. });
  60997. }
  60998. var target;
  60999. if (this._shareOutputWithPostProcess) {
  61000. target = this._shareOutputWithPostProcess.inputTexture;
  61001. }
  61002. else if (this._forcedOutputTexture) {
  61003. target = this._forcedOutputTexture;
  61004. this.width = this._forcedOutputTexture.width;
  61005. this.height = this._forcedOutputTexture.height;
  61006. }
  61007. else {
  61008. target = this.inputTexture;
  61009. }
  61010. // Bind the input of this post process to be used as the output of the previous post process.
  61011. if (this.enablePixelPerfectMode) {
  61012. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  61013. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  61014. }
  61015. else {
  61016. this._scaleRatio.copyFromFloats(1, 1);
  61017. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  61018. }
  61019. this.onActivateObservable.notifyObservers(camera);
  61020. // Clear
  61021. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  61022. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  61023. }
  61024. if (this._reusable) {
  61025. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  61026. }
  61027. return target;
  61028. };
  61029. Object.defineProperty(PostProcess.prototype, "isSupported", {
  61030. /**
  61031. * If the post process is supported.
  61032. */
  61033. get: function () {
  61034. return this._effect.isSupported;
  61035. },
  61036. enumerable: true,
  61037. configurable: true
  61038. });
  61039. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  61040. /**
  61041. * The aspect ratio of the output texture.
  61042. */
  61043. get: function () {
  61044. if (this._shareOutputWithPostProcess) {
  61045. return this._shareOutputWithPostProcess.aspectRatio;
  61046. }
  61047. if (this._forcedOutputTexture) {
  61048. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  61049. }
  61050. return this.width / this.height;
  61051. },
  61052. enumerable: true,
  61053. configurable: true
  61054. });
  61055. /**
  61056. * Get a value indicating if the post-process is ready to be used
  61057. * @returns true if the post-process is ready (shader is compiled)
  61058. */
  61059. PostProcess.prototype.isReady = function () {
  61060. return this._effect && this._effect.isReady();
  61061. };
  61062. /**
  61063. * Binds all textures and uniforms to the shader, this will be run on every pass.
  61064. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  61065. */
  61066. PostProcess.prototype.apply = function () {
  61067. // Check
  61068. if (!this._effect || !this._effect.isReady())
  61069. return null;
  61070. // States
  61071. this._engine.enableEffect(this._effect);
  61072. this._engine.setState(false);
  61073. this._engine.setDepthBuffer(false);
  61074. this._engine.setDepthWrite(false);
  61075. // Alpha
  61076. this._engine.setAlphaMode(this.alphaMode);
  61077. if (this.alphaConstants) {
  61078. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  61079. }
  61080. // Bind the output texture of the preivous post process as the input to this post process.
  61081. var source;
  61082. if (this._shareOutputWithPostProcess) {
  61083. source = this._shareOutputWithPostProcess.inputTexture;
  61084. }
  61085. else if (this._forcedOutputTexture) {
  61086. source = this._forcedOutputTexture;
  61087. }
  61088. else {
  61089. source = this.inputTexture;
  61090. }
  61091. this._effect._bindTexture("textureSampler", source);
  61092. // Parameters
  61093. this._effect.setVector2("scale", this._scaleRatio);
  61094. this.onApplyObservable.notifyObservers(this._effect);
  61095. return this._effect;
  61096. };
  61097. PostProcess.prototype._disposeTextures = function () {
  61098. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  61099. return;
  61100. }
  61101. if (this._textures.length > 0) {
  61102. for (var i = 0; i < this._textures.length; i++) {
  61103. this._engine._releaseTexture(this._textures.data[i]);
  61104. }
  61105. }
  61106. this._textures.dispose();
  61107. };
  61108. /**
  61109. * Disposes the post process.
  61110. * @param camera The camera to dispose the post process on.
  61111. */
  61112. PostProcess.prototype.dispose = function (camera) {
  61113. camera = camera || this._camera;
  61114. this._disposeTextures();
  61115. if (this._scene) {
  61116. var index_1 = this._scene.postProcesses.indexOf(this);
  61117. if (index_1 !== -1) {
  61118. this._scene.postProcesses.splice(index_1, 1);
  61119. }
  61120. }
  61121. else {
  61122. var index_2 = this._engine.postProcesses.indexOf(this);
  61123. if (index_2 !== -1) {
  61124. this._engine.postProcesses.splice(index_2, 1);
  61125. }
  61126. }
  61127. if (!camera) {
  61128. return;
  61129. }
  61130. camera.detachPostProcess(this);
  61131. var index = camera._postProcesses.indexOf(this);
  61132. if (index === 0 && camera._postProcesses.length > 0) {
  61133. var firstPostProcess = this._camera._getFirstPostProcess();
  61134. if (firstPostProcess) {
  61135. firstPostProcess.markTextureDirty();
  61136. }
  61137. }
  61138. this.onActivateObservable.clear();
  61139. this.onAfterRenderObservable.clear();
  61140. this.onApplyObservable.clear();
  61141. this.onBeforeRenderObservable.clear();
  61142. this.onSizeChangedObservable.clear();
  61143. };
  61144. return PostProcess;
  61145. }());
  61146. BABYLON.PostProcess = PostProcess;
  61147. })(BABYLON || (BABYLON = {}));
  61148. //# sourceMappingURL=babylon.postProcess.js.map
  61149. "use strict";
  61150. var BABYLON;
  61151. (function (BABYLON) {
  61152. var PassPostProcess = /** @class */ (function (_super) {
  61153. __extends(PassPostProcess, _super);
  61154. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  61155. if (camera === void 0) { camera = null; }
  61156. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61157. if (blockCompilation === void 0) { blockCompilation = false; }
  61158. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  61159. }
  61160. return PassPostProcess;
  61161. }(BABYLON.PostProcess));
  61162. BABYLON.PassPostProcess = PassPostProcess;
  61163. })(BABYLON || (BABYLON = {}));
  61164. //# sourceMappingURL=babylon.passPostProcess.js.map
  61165. "use strict";
  61166. var __assign = (this && this.__assign) || Object.assign || function(t) {
  61167. for (var s, i = 1, n = arguments.length; i < n; i++) {
  61168. s = arguments[i];
  61169. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  61170. t[p] = s[p];
  61171. }
  61172. return t;
  61173. };
  61174. var BABYLON;
  61175. (function (BABYLON) {
  61176. /**
  61177. * Default implementation of @see IShadowGenerator.
  61178. * This is the main object responsible of generating shadows in the framework.
  61179. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  61180. */
  61181. var ShadowGenerator = /** @class */ (function () {
  61182. /**
  61183. * Creates a ShadowGenerator object.
  61184. * A ShadowGenerator is the required tool to use the shadows.
  61185. * Each light casting shadows needs to use its own ShadowGenerator.
  61186. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  61187. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  61188. * @param light The light object generating the shadows.
  61189. * @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.
  61190. */
  61191. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  61192. this._bias = 0.00005;
  61193. this._normalBias = 0;
  61194. this._blurBoxOffset = 1;
  61195. this._blurScale = 2;
  61196. this._blurKernel = 1;
  61197. this._useKernelBlur = false;
  61198. this._filter = ShadowGenerator.FILTER_NONE;
  61199. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  61200. this._contactHardeningLightSizeUVRatio = 0.1;
  61201. this._darkness = 0;
  61202. this._transparencyShadow = false;
  61203. /**
  61204. * Controls the extent to which the shadows fade out at the edge of the frustum
  61205. * Used only by directionals and spots
  61206. */
  61207. this.frustumEdgeFalloff = 0;
  61208. /**
  61209. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  61210. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  61211. * It might on the other hand introduce peter panning.
  61212. */
  61213. this.forceBackFacesOnly = false;
  61214. this._lightDirection = BABYLON.Vector3.Zero();
  61215. this._viewMatrix = BABYLON.Matrix.Zero();
  61216. this._projectionMatrix = BABYLON.Matrix.Zero();
  61217. this._transformMatrix = BABYLON.Matrix.Zero();
  61218. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61219. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61220. this._currentFaceIndex = 0;
  61221. this._currentFaceIndexCache = 0;
  61222. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  61223. this._mapSize = mapSize;
  61224. this._light = light;
  61225. this._scene = light.getScene();
  61226. light._shadowGenerator = this;
  61227. // Texture type fallback from float to int if not supported.
  61228. var caps = this._scene.getEngine().getCaps();
  61229. if (!useFullFloatFirst) {
  61230. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61231. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61232. }
  61233. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61234. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61235. }
  61236. else {
  61237. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61238. }
  61239. }
  61240. else {
  61241. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61242. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61243. }
  61244. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61245. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61246. }
  61247. else {
  61248. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61249. }
  61250. }
  61251. this._initializeGenerator();
  61252. this._applyFilterValues();
  61253. }
  61254. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  61255. /**
  61256. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  61257. */
  61258. get: function () {
  61259. return this._bias;
  61260. },
  61261. /**
  61262. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  61263. */
  61264. set: function (bias) {
  61265. this._bias = bias;
  61266. },
  61267. enumerable: true,
  61268. configurable: true
  61269. });
  61270. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  61271. /**
  61272. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61273. */
  61274. get: function () {
  61275. return this._normalBias;
  61276. },
  61277. /**
  61278. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61279. */
  61280. set: function (normalBias) {
  61281. this._normalBias = normalBias;
  61282. },
  61283. enumerable: true,
  61284. configurable: true
  61285. });
  61286. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61287. /**
  61288. * Gets the blur box offset: offset applied during the blur pass.
  61289. * Only usefull if useKernelBlur = false
  61290. */
  61291. get: function () {
  61292. return this._blurBoxOffset;
  61293. },
  61294. /**
  61295. * Sets the blur box offset: offset applied during the blur pass.
  61296. * Only usefull if useKernelBlur = false
  61297. */
  61298. set: function (value) {
  61299. if (this._blurBoxOffset === value) {
  61300. return;
  61301. }
  61302. this._blurBoxOffset = value;
  61303. this._disposeBlurPostProcesses();
  61304. },
  61305. enumerable: true,
  61306. configurable: true
  61307. });
  61308. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61309. /**
  61310. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61311. * 2 means half of the size.
  61312. */
  61313. get: function () {
  61314. return this._blurScale;
  61315. },
  61316. /**
  61317. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61318. * 2 means half of the size.
  61319. */
  61320. set: function (value) {
  61321. if (this._blurScale === value) {
  61322. return;
  61323. }
  61324. this._blurScale = value;
  61325. this._disposeBlurPostProcesses();
  61326. },
  61327. enumerable: true,
  61328. configurable: true
  61329. });
  61330. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61331. /**
  61332. * Gets the blur kernel: kernel size of the blur pass.
  61333. * Only usefull if useKernelBlur = true
  61334. */
  61335. get: function () {
  61336. return this._blurKernel;
  61337. },
  61338. /**
  61339. * Sets the blur kernel: kernel size of the blur pass.
  61340. * Only usefull if useKernelBlur = true
  61341. */
  61342. set: function (value) {
  61343. if (this._blurKernel === value) {
  61344. return;
  61345. }
  61346. this._blurKernel = value;
  61347. this._disposeBlurPostProcesses();
  61348. },
  61349. enumerable: true,
  61350. configurable: true
  61351. });
  61352. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61353. /**
  61354. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61355. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61356. */
  61357. get: function () {
  61358. return this._useKernelBlur;
  61359. },
  61360. /**
  61361. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61362. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61363. */
  61364. set: function (value) {
  61365. if (this._useKernelBlur === value) {
  61366. return;
  61367. }
  61368. this._useKernelBlur = value;
  61369. this._disposeBlurPostProcesses();
  61370. },
  61371. enumerable: true,
  61372. configurable: true
  61373. });
  61374. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61375. /**
  61376. * Gets the depth scale used in ESM mode.
  61377. */
  61378. get: function () {
  61379. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61380. },
  61381. /**
  61382. * Sets the depth scale used in ESM mode.
  61383. * This can override the scale stored on the light.
  61384. */
  61385. set: function (value) {
  61386. this._depthScale = value;
  61387. },
  61388. enumerable: true,
  61389. configurable: true
  61390. });
  61391. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61392. /**
  61393. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61394. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61395. */
  61396. get: function () {
  61397. return this._filter;
  61398. },
  61399. /**
  61400. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61401. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61402. */
  61403. set: function (value) {
  61404. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61405. if (this._light.needCube()) {
  61406. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61407. this.useExponentialShadowMap = true;
  61408. return;
  61409. }
  61410. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61411. this.useCloseExponentialShadowMap = true;
  61412. return;
  61413. }
  61414. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61415. this.usePoissonSampling = true;
  61416. return;
  61417. }
  61418. }
  61419. // Weblg1 fallback for PCF.
  61420. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61421. if (this._scene.getEngine().webGLVersion === 1) {
  61422. this.usePoissonSampling = true;
  61423. return;
  61424. }
  61425. }
  61426. if (this._filter === value) {
  61427. return;
  61428. }
  61429. this._filter = value;
  61430. this._disposeBlurPostProcesses();
  61431. this._applyFilterValues();
  61432. this._light._markMeshesAsLightDirty();
  61433. },
  61434. enumerable: true,
  61435. configurable: true
  61436. });
  61437. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61438. /**
  61439. * Gets if the current filter is set to Poisson Sampling.
  61440. */
  61441. get: function () {
  61442. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61443. },
  61444. /**
  61445. * Sets the current filter to Poisson Sampling.
  61446. */
  61447. set: function (value) {
  61448. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61449. return;
  61450. }
  61451. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61452. },
  61453. enumerable: true,
  61454. configurable: true
  61455. });
  61456. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61457. /**
  61458. * Gets if the current filter is set to VSM.
  61459. * DEPRECATED. Should use useExponentialShadowMap instead.
  61460. */
  61461. get: function () {
  61462. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61463. return this.useExponentialShadowMap;
  61464. },
  61465. /**
  61466. * Sets the current filter is to VSM.
  61467. * DEPRECATED. Should use useExponentialShadowMap instead.
  61468. */
  61469. set: function (value) {
  61470. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61471. this.useExponentialShadowMap = value;
  61472. },
  61473. enumerable: true,
  61474. configurable: true
  61475. });
  61476. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61477. /**
  61478. * Gets if the current filter is set to blurred VSM.
  61479. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61480. */
  61481. get: function () {
  61482. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61483. return this.useBlurExponentialShadowMap;
  61484. },
  61485. /**
  61486. * Sets the current filter is to blurred VSM.
  61487. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61488. */
  61489. set: function (value) {
  61490. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61491. this.useBlurExponentialShadowMap = value;
  61492. },
  61493. enumerable: true,
  61494. configurable: true
  61495. });
  61496. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61497. /**
  61498. * Gets if the current filter is set to ESM.
  61499. */
  61500. get: function () {
  61501. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61502. },
  61503. /**
  61504. * Sets the current filter is to ESM.
  61505. */
  61506. set: function (value) {
  61507. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61508. return;
  61509. }
  61510. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61511. },
  61512. enumerable: true,
  61513. configurable: true
  61514. });
  61515. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61516. /**
  61517. * Gets if the current filter is set to filtered ESM.
  61518. */
  61519. get: function () {
  61520. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61521. },
  61522. /**
  61523. * Gets if the current filter is set to filtered ESM.
  61524. */
  61525. set: function (value) {
  61526. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61527. return;
  61528. }
  61529. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61530. },
  61531. enumerable: true,
  61532. configurable: true
  61533. });
  61534. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61535. /**
  61536. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61537. * exponential to prevent steep falloff artifacts).
  61538. */
  61539. get: function () {
  61540. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61541. },
  61542. /**
  61543. * Sets the current filter to "close ESM" (using the inverse of the
  61544. * exponential to prevent steep falloff artifacts).
  61545. */
  61546. set: function (value) {
  61547. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61548. return;
  61549. }
  61550. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61551. },
  61552. enumerable: true,
  61553. configurable: true
  61554. });
  61555. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61556. /**
  61557. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61558. * exponential to prevent steep falloff artifacts).
  61559. */
  61560. get: function () {
  61561. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61562. },
  61563. /**
  61564. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61565. * exponential to prevent steep falloff artifacts).
  61566. */
  61567. set: function (value) {
  61568. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61569. return;
  61570. }
  61571. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61572. },
  61573. enumerable: true,
  61574. configurable: true
  61575. });
  61576. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61577. /**
  61578. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61579. */
  61580. get: function () {
  61581. return this.filter === ShadowGenerator.FILTER_PCF;
  61582. },
  61583. /**
  61584. * Sets the current filter to "PCF" (percentage closer filtering).
  61585. */
  61586. set: function (value) {
  61587. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61588. return;
  61589. }
  61590. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61591. },
  61592. enumerable: true,
  61593. configurable: true
  61594. });
  61595. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61596. /**
  61597. * Gets the PCF or PCSS Quality.
  61598. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61599. */
  61600. get: function () {
  61601. return this._filteringQuality;
  61602. },
  61603. /**
  61604. * Sets the PCF or PCSS Quality.
  61605. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61606. */
  61607. set: function (filteringQuality) {
  61608. this._filteringQuality = filteringQuality;
  61609. },
  61610. enumerable: true,
  61611. configurable: true
  61612. });
  61613. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61614. /**
  61615. * Gets if the current filter is set to "PCSS" (contact hardening).
  61616. */
  61617. get: function () {
  61618. return this.filter === ShadowGenerator.FILTER_PCSS;
  61619. },
  61620. /**
  61621. * Sets the current filter to "PCSS" (contact hardening).
  61622. */
  61623. set: function (value) {
  61624. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61625. return;
  61626. }
  61627. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61628. },
  61629. enumerable: true,
  61630. configurable: true
  61631. });
  61632. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61633. /**
  61634. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61635. * Using a ratio helps keeping shape stability independently of the map size.
  61636. *
  61637. * It does not account for the light projection as it was having too much
  61638. * instability during the light setup or during light position changes.
  61639. *
  61640. * Only valid if useContactHardeningShadow is true.
  61641. */
  61642. get: function () {
  61643. return this._contactHardeningLightSizeUVRatio;
  61644. },
  61645. /**
  61646. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61647. * Using a ratio helps keeping shape stability independently of the map size.
  61648. *
  61649. * It does not account for the light projection as it was having too much
  61650. * instability during the light setup or during light position changes.
  61651. *
  61652. * Only valid if useContactHardeningShadow is true.
  61653. */
  61654. set: function (contactHardeningLightSizeUVRatio) {
  61655. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61656. },
  61657. enumerable: true,
  61658. configurable: true
  61659. });
  61660. /**
  61661. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61662. * 0 means strongest and 1 would means no shadow.
  61663. * @returns the darkness.
  61664. */
  61665. ShadowGenerator.prototype.getDarkness = function () {
  61666. return this._darkness;
  61667. };
  61668. /**
  61669. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61670. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61671. * @returns the shadow generator allowing fluent coding.
  61672. */
  61673. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61674. if (darkness >= 1.0)
  61675. this._darkness = 1.0;
  61676. else if (darkness <= 0.0)
  61677. this._darkness = 0.0;
  61678. else
  61679. this._darkness = darkness;
  61680. return this;
  61681. };
  61682. /**
  61683. * Sets the ability to have transparent shadow (boolean).
  61684. * @param transparent True if transparent else False
  61685. * @returns the shadow generator allowing fluent coding
  61686. */
  61687. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61688. this._transparencyShadow = transparent;
  61689. return this;
  61690. };
  61691. /**
  61692. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61693. * @returns The render target texture if present otherwise, null
  61694. */
  61695. ShadowGenerator.prototype.getShadowMap = function () {
  61696. return this._shadowMap;
  61697. };
  61698. /**
  61699. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61700. * @returns The render target texture if the shadow map is present otherwise, null
  61701. */
  61702. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61703. if (this._shadowMap2) {
  61704. return this._shadowMap2;
  61705. }
  61706. return this._shadowMap;
  61707. };
  61708. /**
  61709. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61710. * @param mesh Mesh to add
  61711. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61712. * @returns the Shadow Generator itself
  61713. */
  61714. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61715. if (includeDescendants === void 0) { includeDescendants = true; }
  61716. if (!this._shadowMap) {
  61717. return this;
  61718. }
  61719. if (!this._shadowMap.renderList) {
  61720. this._shadowMap.renderList = [];
  61721. }
  61722. this._shadowMap.renderList.push(mesh);
  61723. if (includeDescendants) {
  61724. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61725. }
  61726. return this;
  61727. var _a;
  61728. };
  61729. /**
  61730. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61731. * @param mesh Mesh to remove
  61732. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61733. * @returns the Shadow Generator itself
  61734. */
  61735. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61736. if (includeDescendants === void 0) { includeDescendants = true; }
  61737. if (!this._shadowMap || !this._shadowMap.renderList) {
  61738. return this;
  61739. }
  61740. var index = this._shadowMap.renderList.indexOf(mesh);
  61741. if (index !== -1) {
  61742. this._shadowMap.renderList.splice(index, 1);
  61743. }
  61744. if (includeDescendants) {
  61745. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61746. var child = _a[_i];
  61747. this.removeShadowCaster(child);
  61748. }
  61749. }
  61750. return this;
  61751. };
  61752. /**
  61753. * Returns the associated light object.
  61754. * @returns the light generating the shadow
  61755. */
  61756. ShadowGenerator.prototype.getLight = function () {
  61757. return this._light;
  61758. };
  61759. ShadowGenerator.prototype._initializeGenerator = function () {
  61760. this._light._markMeshesAsLightDirty();
  61761. this._initializeShadowMap();
  61762. };
  61763. ShadowGenerator.prototype._initializeShadowMap = function () {
  61764. var _this = this;
  61765. // Render target
  61766. var engine = this._scene.getEngine();
  61767. if (engine.webGLVersion > 1) {
  61768. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61769. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61770. }
  61771. else {
  61772. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61773. }
  61774. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61775. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61776. this._shadowMap.anisotropicFilteringLevel = 1;
  61777. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61778. this._shadowMap.renderParticles = false;
  61779. this._shadowMap.ignoreCameraViewport = true;
  61780. // Record Face Index before render.
  61781. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61782. _this._currentFaceIndex = faceIndex;
  61783. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61784. engine.setColorWrite(false);
  61785. }
  61786. });
  61787. // Custom render function.
  61788. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61789. // Blur if required afer render.
  61790. this._shadowMap.onAfterUnbindObservable.add(function () {
  61791. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61792. engine.setColorWrite(true);
  61793. }
  61794. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61795. return;
  61796. }
  61797. var shadowMap = _this.getShadowMapForRendering();
  61798. if (shadowMap) {
  61799. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61800. }
  61801. });
  61802. // Clear according to the chosen filter.
  61803. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61804. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61805. this._shadowMap.onClearObservable.add(function (engine) {
  61806. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61807. engine.clear(clearOne, false, true, false);
  61808. }
  61809. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61810. engine.clear(clearZero, true, true, false);
  61811. }
  61812. else {
  61813. engine.clear(clearOne, true, true, false);
  61814. }
  61815. });
  61816. };
  61817. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61818. var _this = this;
  61819. var engine = this._scene.getEngine();
  61820. var targetSize = this._mapSize / this.blurScale;
  61821. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61822. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61823. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61824. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61825. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61826. }
  61827. if (this.useKernelBlur) {
  61828. 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);
  61829. this._kernelBlurXPostprocess.width = targetSize;
  61830. this._kernelBlurXPostprocess.height = targetSize;
  61831. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61832. effect.setTexture("textureSampler", _this._shadowMap);
  61833. });
  61834. 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);
  61835. this._kernelBlurXPostprocess.autoClear = false;
  61836. this._kernelBlurYPostprocess.autoClear = false;
  61837. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61838. this._kernelBlurXPostprocess.packedFloat = true;
  61839. this._kernelBlurYPostprocess.packedFloat = true;
  61840. }
  61841. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61842. }
  61843. else {
  61844. 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);
  61845. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61846. effect.setFloat2("screenSize", targetSize, targetSize);
  61847. effect.setTexture("textureSampler", _this._shadowMap);
  61848. });
  61849. this._boxBlurPostprocess.autoClear = false;
  61850. this._blurPostProcesses = [this._boxBlurPostprocess];
  61851. }
  61852. };
  61853. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61854. var index;
  61855. var engine = this._scene.getEngine();
  61856. if (depthOnlySubMeshes.length) {
  61857. engine.setColorWrite(false);
  61858. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61859. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61860. }
  61861. engine.setColorWrite(true);
  61862. }
  61863. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61864. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61865. }
  61866. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61867. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61868. }
  61869. if (this._transparencyShadow) {
  61870. for (index = 0; index < transparentSubMeshes.length; index++) {
  61871. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61872. }
  61873. }
  61874. };
  61875. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61876. var _this = this;
  61877. var mesh = subMesh.getRenderingMesh();
  61878. var scene = this._scene;
  61879. var engine = scene.getEngine();
  61880. var material = subMesh.getMaterial();
  61881. if (!material) {
  61882. return;
  61883. }
  61884. // Culling
  61885. engine.setState(material.backFaceCulling);
  61886. // Managing instances
  61887. var batch = mesh._getInstancesRenderList(subMesh._id);
  61888. if (batch.mustReturn) {
  61889. return;
  61890. }
  61891. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61892. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61893. engine.enableEffect(this._effect);
  61894. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61895. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61896. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61897. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61898. this._effect.setVector3("lightData", this._cachedDirection);
  61899. }
  61900. else {
  61901. this._effect.setVector3("lightData", this._cachedPosition);
  61902. }
  61903. if (scene.activeCamera) {
  61904. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61905. }
  61906. // Alpha test
  61907. if (material && material.needAlphaTesting()) {
  61908. var alphaTexture = material.getAlphaTestTexture();
  61909. if (alphaTexture) {
  61910. this._effect.setTexture("diffuseSampler", alphaTexture);
  61911. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61912. }
  61913. }
  61914. // Bones
  61915. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61916. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61917. }
  61918. // Morph targets
  61919. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  61920. if (this.forceBackFacesOnly) {
  61921. engine.setState(true, 0, false, true);
  61922. }
  61923. // Draw
  61924. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61925. if (this.forceBackFacesOnly) {
  61926. engine.setState(true, 0, false, false);
  61927. }
  61928. }
  61929. else {
  61930. // Need to reset refresh rate of the shadowMap
  61931. if (this._shadowMap) {
  61932. this._shadowMap.resetRefreshCounter();
  61933. }
  61934. }
  61935. };
  61936. ShadowGenerator.prototype._applyFilterValues = function () {
  61937. if (!this._shadowMap) {
  61938. return;
  61939. }
  61940. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61941. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61942. }
  61943. else {
  61944. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61945. }
  61946. };
  61947. /**
  61948. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61949. * @param onCompiled Callback triggered at the and of the effects compilation
  61950. * @param options Sets of optional options forcing the compilation with different modes
  61951. */
  61952. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61953. var _this = this;
  61954. var localOptions = __assign({ useInstances: false }, options);
  61955. var shadowMap = this.getShadowMap();
  61956. if (!shadowMap) {
  61957. if (onCompiled) {
  61958. onCompiled(this);
  61959. }
  61960. return;
  61961. }
  61962. var renderList = shadowMap.renderList;
  61963. if (!renderList) {
  61964. if (onCompiled) {
  61965. onCompiled(this);
  61966. }
  61967. return;
  61968. }
  61969. var subMeshes = new Array();
  61970. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61971. var mesh = renderList_1[_i];
  61972. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61973. }
  61974. if (subMeshes.length === 0) {
  61975. if (onCompiled) {
  61976. onCompiled(this);
  61977. }
  61978. return;
  61979. }
  61980. var currentIndex = 0;
  61981. var checkReady = function () {
  61982. if (!_this._scene || !_this._scene.getEngine()) {
  61983. return;
  61984. }
  61985. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61986. currentIndex++;
  61987. if (currentIndex >= subMeshes.length) {
  61988. if (onCompiled) {
  61989. onCompiled(_this);
  61990. }
  61991. return;
  61992. }
  61993. }
  61994. setTimeout(checkReady, 16);
  61995. };
  61996. checkReady();
  61997. };
  61998. /**
  61999. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  62000. * @param options Sets of optional options forcing the compilation with different modes
  62001. * @returns A promise that resolves when the compilation completes
  62002. */
  62003. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  62004. var _this = this;
  62005. return new Promise(function (resolve) {
  62006. _this.forceCompilation(function () {
  62007. resolve();
  62008. }, options);
  62009. });
  62010. };
  62011. /**
  62012. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  62013. * @param subMesh The submesh we want to render in the shadow map
  62014. * @param useInstances Defines wether will draw in the map using instances
  62015. * @returns true if ready otherwise, false
  62016. */
  62017. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  62018. var defines = [];
  62019. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62020. defines.push("#define FLOAT");
  62021. }
  62022. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62023. defines.push("#define ESM");
  62024. }
  62025. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  62026. defines.push("#define DEPTHTEXTURE");
  62027. }
  62028. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62029. var mesh = subMesh.getMesh();
  62030. var material = subMesh.getMaterial();
  62031. // Normal bias.
  62032. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62033. attribs.push(BABYLON.VertexBuffer.NormalKind);
  62034. defines.push("#define NORMAL");
  62035. if (mesh.nonUniformScaling) {
  62036. defines.push("#define NONUNIFORMSCALING");
  62037. }
  62038. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  62039. defines.push("#define DIRECTIONINLIGHTDATA");
  62040. }
  62041. }
  62042. // Alpha test
  62043. if (material && material.needAlphaTesting()) {
  62044. var alphaTexture = material.getAlphaTestTexture();
  62045. if (alphaTexture) {
  62046. defines.push("#define ALPHATEST");
  62047. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62048. attribs.push(BABYLON.VertexBuffer.UVKind);
  62049. defines.push("#define UV1");
  62050. }
  62051. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62052. if (alphaTexture.coordinatesIndex === 1) {
  62053. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62054. defines.push("#define UV2");
  62055. }
  62056. }
  62057. }
  62058. }
  62059. // Bones
  62060. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62061. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62062. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62063. if (mesh.numBoneInfluencers > 4) {
  62064. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62065. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62066. }
  62067. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62068. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62069. }
  62070. else {
  62071. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62072. }
  62073. // Morph targets
  62074. var manager = mesh.morphTargetManager;
  62075. var morphInfluencers = 0;
  62076. if (manager) {
  62077. if (manager.numInfluencers > 0) {
  62078. defines.push("#define MORPHTARGETS");
  62079. morphInfluencers = manager.numInfluencers;
  62080. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  62081. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  62082. }
  62083. }
  62084. // Instances
  62085. if (useInstances) {
  62086. defines.push("#define INSTANCES");
  62087. attribs.push("world0");
  62088. attribs.push("world1");
  62089. attribs.push("world2");
  62090. attribs.push("world3");
  62091. }
  62092. // Get correct effect
  62093. var join = defines.join("\n");
  62094. if (this._cachedDefines !== join) {
  62095. this._cachedDefines = join;
  62096. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  62097. }
  62098. if (!this._effect.isReady()) {
  62099. return false;
  62100. }
  62101. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62102. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  62103. this._initializeBlurRTTAndPostProcesses();
  62104. }
  62105. }
  62106. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  62107. return false;
  62108. }
  62109. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  62110. return false;
  62111. }
  62112. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  62113. return false;
  62114. }
  62115. return true;
  62116. };
  62117. /**
  62118. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  62119. * @param defines Defines of the material we want to update
  62120. * @param lightIndex Index of the light in the enabled light list of the material
  62121. */
  62122. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  62123. var scene = this._scene;
  62124. var light = this._light;
  62125. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62126. return;
  62127. }
  62128. defines["SHADOW" + lightIndex] = true;
  62129. if (this.useContactHardeningShadow) {
  62130. defines["SHADOWPCSS" + lightIndex] = true;
  62131. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62132. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62133. }
  62134. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62135. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62136. }
  62137. // else default to high.
  62138. }
  62139. if (this.usePercentageCloserFiltering) {
  62140. defines["SHADOWPCF" + lightIndex] = true;
  62141. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62142. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62143. }
  62144. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62145. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62146. }
  62147. // else default to high.
  62148. }
  62149. else if (this.usePoissonSampling) {
  62150. defines["SHADOWPOISSON" + lightIndex] = true;
  62151. }
  62152. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62153. defines["SHADOWESM" + lightIndex] = true;
  62154. }
  62155. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62156. defines["SHADOWCLOSEESM" + lightIndex] = true;
  62157. }
  62158. if (light.needCube()) {
  62159. defines["SHADOWCUBE" + lightIndex] = true;
  62160. }
  62161. };
  62162. /**
  62163. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  62164. * defined in the generator but impacting the effect).
  62165. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  62166. * @param effect The effect we are binfing the information for
  62167. */
  62168. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  62169. var light = this._light;
  62170. var scene = this._scene;
  62171. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62172. return;
  62173. }
  62174. var camera = scene.activeCamera;
  62175. if (!camera) {
  62176. return;
  62177. }
  62178. var shadowMap = this.getShadowMap();
  62179. if (!shadowMap) {
  62180. return;
  62181. }
  62182. if (!light.needCube()) {
  62183. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  62184. }
  62185. // Only PCF uses depth stencil texture.
  62186. if (this._filter === ShadowGenerator.FILTER_PCF) {
  62187. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62188. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62189. }
  62190. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  62191. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62192. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  62193. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62194. }
  62195. else {
  62196. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62197. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  62198. }
  62199. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  62200. };
  62201. /**
  62202. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  62203. * (eq to shadow prjection matrix * light transform matrix)
  62204. * @returns The transform matrix used to create the shadow map
  62205. */
  62206. ShadowGenerator.prototype.getTransformMatrix = function () {
  62207. var scene = this._scene;
  62208. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  62209. return this._transformMatrix;
  62210. }
  62211. this._currentRenderID = scene.getRenderId();
  62212. this._currentFaceIndexCache = this._currentFaceIndex;
  62213. var lightPosition = this._light.position;
  62214. if (this._light.computeTransformedInformation()) {
  62215. lightPosition = this._light.transformedPosition;
  62216. }
  62217. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  62218. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  62219. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  62220. }
  62221. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  62222. this._cachedPosition.copyFrom(lightPosition);
  62223. this._cachedDirection.copyFrom(this._lightDirection);
  62224. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  62225. var shadowMap = this.getShadowMap();
  62226. if (shadowMap) {
  62227. var renderList = shadowMap.renderList;
  62228. if (renderList) {
  62229. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  62230. }
  62231. }
  62232. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  62233. }
  62234. return this._transformMatrix;
  62235. };
  62236. /**
  62237. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  62238. * Cube and 2D textures for instance.
  62239. */
  62240. ShadowGenerator.prototype.recreateShadowMap = function () {
  62241. var shadowMap = this._shadowMap;
  62242. if (!shadowMap) {
  62243. return;
  62244. }
  62245. // Track render list.
  62246. var renderList = shadowMap.renderList;
  62247. // Clean up existing data.
  62248. this._disposeRTTandPostProcesses();
  62249. // Reinitializes.
  62250. this._initializeGenerator();
  62251. // Reaffect the filter to ensure a correct fallback if necessary.
  62252. this.filter = this.filter;
  62253. // Reaffect the filter.
  62254. this._applyFilterValues();
  62255. // Reaffect Render List.
  62256. this._shadowMap.renderList = renderList;
  62257. };
  62258. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  62259. if (this._shadowMap2) {
  62260. this._shadowMap2.dispose();
  62261. this._shadowMap2 = null;
  62262. }
  62263. if (this._boxBlurPostprocess) {
  62264. this._boxBlurPostprocess.dispose();
  62265. this._boxBlurPostprocess = null;
  62266. }
  62267. if (this._kernelBlurXPostprocess) {
  62268. this._kernelBlurXPostprocess.dispose();
  62269. this._kernelBlurXPostprocess = null;
  62270. }
  62271. if (this._kernelBlurYPostprocess) {
  62272. this._kernelBlurYPostprocess.dispose();
  62273. this._kernelBlurYPostprocess = null;
  62274. }
  62275. this._blurPostProcesses = [];
  62276. };
  62277. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  62278. if (this._shadowMap) {
  62279. this._shadowMap.dispose();
  62280. this._shadowMap = null;
  62281. }
  62282. this._disposeBlurPostProcesses();
  62283. };
  62284. /**
  62285. * Disposes the ShadowGenerator.
  62286. * Returns nothing.
  62287. */
  62288. ShadowGenerator.prototype.dispose = function () {
  62289. this._disposeRTTandPostProcesses();
  62290. if (this._light) {
  62291. this._light._shadowGenerator = null;
  62292. this._light._markMeshesAsLightDirty();
  62293. }
  62294. };
  62295. /**
  62296. * Serializes the shadow generator setup to a json object.
  62297. * @returns The serialized JSON object
  62298. */
  62299. ShadowGenerator.prototype.serialize = function () {
  62300. var serializationObject = {};
  62301. var shadowMap = this.getShadowMap();
  62302. if (!shadowMap) {
  62303. return serializationObject;
  62304. }
  62305. serializationObject.lightId = this._light.id;
  62306. serializationObject.mapSize = shadowMap.getRenderSize();
  62307. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62308. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62309. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62310. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62311. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62312. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62313. serializationObject.depthScale = this.depthScale;
  62314. serializationObject.darkness = this.getDarkness();
  62315. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62316. serializationObject.blurKernel = this.blurKernel;
  62317. serializationObject.blurScale = this.blurScale;
  62318. serializationObject.useKernelBlur = this.useKernelBlur;
  62319. serializationObject.transparencyShadow = this._transparencyShadow;
  62320. serializationObject.bias = this.bias;
  62321. serializationObject.normalBias = this.normalBias;
  62322. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62323. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62324. serializationObject.filteringQuality = this.filteringQuality;
  62325. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62326. serializationObject.renderList = [];
  62327. if (shadowMap.renderList) {
  62328. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62329. var mesh = shadowMap.renderList[meshIndex];
  62330. serializationObject.renderList.push(mesh.id);
  62331. }
  62332. }
  62333. return serializationObject;
  62334. };
  62335. /**
  62336. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62337. * @param parsedShadowGenerator The JSON object to parse
  62338. * @param scene The scene to create the shadow map for
  62339. * @returns The parsed shadow generator
  62340. */
  62341. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62342. //casting to point light, as light is missing the position attr and typescript complains.
  62343. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62344. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62345. var shadowMap = shadowGenerator.getShadowMap();
  62346. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62347. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62348. meshes.forEach(function (mesh) {
  62349. if (!shadowMap) {
  62350. return;
  62351. }
  62352. if (!shadowMap.renderList) {
  62353. shadowMap.renderList = [];
  62354. }
  62355. shadowMap.renderList.push(mesh);
  62356. });
  62357. }
  62358. if (parsedShadowGenerator.usePoissonSampling) {
  62359. shadowGenerator.usePoissonSampling = true;
  62360. }
  62361. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62362. shadowGenerator.useExponentialShadowMap = true;
  62363. }
  62364. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62365. shadowGenerator.useBlurExponentialShadowMap = true;
  62366. }
  62367. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62368. shadowGenerator.useCloseExponentialShadowMap = true;
  62369. }
  62370. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62371. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62372. }
  62373. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62374. shadowGenerator.usePercentageCloserFiltering = true;
  62375. }
  62376. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62377. shadowGenerator.useContactHardeningShadow = true;
  62378. }
  62379. if (parsedShadowGenerator.filteringQuality) {
  62380. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62381. }
  62382. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62383. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62384. }
  62385. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62386. shadowGenerator.useExponentialShadowMap = true;
  62387. }
  62388. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62389. shadowGenerator.useBlurExponentialShadowMap = true;
  62390. }
  62391. if (parsedShadowGenerator.depthScale) {
  62392. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62393. }
  62394. if (parsedShadowGenerator.blurScale) {
  62395. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62396. }
  62397. if (parsedShadowGenerator.blurBoxOffset) {
  62398. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62399. }
  62400. if (parsedShadowGenerator.useKernelBlur) {
  62401. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62402. }
  62403. if (parsedShadowGenerator.blurKernel) {
  62404. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62405. }
  62406. if (parsedShadowGenerator.bias !== undefined) {
  62407. shadowGenerator.bias = parsedShadowGenerator.bias;
  62408. }
  62409. if (parsedShadowGenerator.normalBias !== undefined) {
  62410. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62411. }
  62412. if (parsedShadowGenerator.darkness) {
  62413. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62414. }
  62415. if (parsedShadowGenerator.transparencyShadow) {
  62416. shadowGenerator.setTransparencyShadow(true);
  62417. }
  62418. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62419. return shadowGenerator;
  62420. };
  62421. /**
  62422. * Shadow generator mode None: no filtering applied.
  62423. */
  62424. ShadowGenerator.FILTER_NONE = 0;
  62425. /**
  62426. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62427. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62428. */
  62429. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62430. /**
  62431. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62432. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62433. */
  62434. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62435. /**
  62436. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62437. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62438. */
  62439. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62440. /**
  62441. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62442. * edge artifacts on steep falloff.
  62443. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62444. */
  62445. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62446. /**
  62447. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62448. * edge artifacts on steep falloff.
  62449. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62450. */
  62451. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62452. /**
  62453. * Shadow generator mode PCF: Percentage Closer Filtering
  62454. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62455. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62456. */
  62457. ShadowGenerator.FILTER_PCF = 6;
  62458. /**
  62459. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62460. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62461. * Contact Hardening
  62462. */
  62463. ShadowGenerator.FILTER_PCSS = 7;
  62464. /**
  62465. * Reserved for PCF and PCSS
  62466. * Highest Quality.
  62467. *
  62468. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62469. *
  62470. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62471. */
  62472. ShadowGenerator.QUALITY_HIGH = 0;
  62473. /**
  62474. * Reserved for PCF and PCSS
  62475. * Good tradeoff for quality/perf cross devices
  62476. *
  62477. * Execute PCF on a 3*3 kernel.
  62478. *
  62479. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62480. */
  62481. ShadowGenerator.QUALITY_MEDIUM = 1;
  62482. /**
  62483. * Reserved for PCF and PCSS
  62484. * The lowest quality but the fastest.
  62485. *
  62486. * Execute PCF on a 1*1 kernel.
  62487. *
  62488. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62489. */
  62490. ShadowGenerator.QUALITY_LOW = 2;
  62491. return ShadowGenerator;
  62492. }());
  62493. BABYLON.ShadowGenerator = ShadowGenerator;
  62494. })(BABYLON || (BABYLON = {}));
  62495. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62496. "use strict";
  62497. var BABYLON;
  62498. (function (BABYLON) {
  62499. var DefaultLoadingScreen = /** @class */ (function () {
  62500. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62501. if (_loadingText === void 0) { _loadingText = ""; }
  62502. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62503. var _this = this;
  62504. this._renderingCanvas = _renderingCanvas;
  62505. this._loadingText = _loadingText;
  62506. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62507. // Resize
  62508. this._resizeLoadingUI = function () {
  62509. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62510. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62511. if (!_this._loadingDiv) {
  62512. return;
  62513. }
  62514. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62515. _this._loadingDiv.style.left = canvasRect.left + "px";
  62516. _this._loadingDiv.style.top = canvasRect.top + "px";
  62517. _this._loadingDiv.style.width = canvasRect.width + "px";
  62518. _this._loadingDiv.style.height = canvasRect.height + "px";
  62519. };
  62520. }
  62521. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62522. if (this._loadingDiv) {
  62523. // Do not add a loading screen if there is already one
  62524. return;
  62525. }
  62526. this._loadingDiv = document.createElement("div");
  62527. this._loadingDiv.id = "babylonjsLoadingDiv";
  62528. this._loadingDiv.style.opacity = "0";
  62529. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62530. this._loadingDiv.style.pointerEvents = "none";
  62531. // Loading text
  62532. this._loadingTextDiv = document.createElement("div");
  62533. this._loadingTextDiv.style.position = "absolute";
  62534. this._loadingTextDiv.style.left = "0";
  62535. this._loadingTextDiv.style.top = "50%";
  62536. this._loadingTextDiv.style.marginTop = "80px";
  62537. this._loadingTextDiv.style.width = "100%";
  62538. this._loadingTextDiv.style.height = "20px";
  62539. this._loadingTextDiv.style.fontFamily = "Arial";
  62540. this._loadingTextDiv.style.fontSize = "14px";
  62541. this._loadingTextDiv.style.color = "white";
  62542. this._loadingTextDiv.style.textAlign = "center";
  62543. this._loadingTextDiv.innerHTML = "Loading";
  62544. this._loadingDiv.appendChild(this._loadingTextDiv);
  62545. //set the predefined text
  62546. this._loadingTextDiv.innerHTML = this._loadingText;
  62547. // Generating keyframes
  62548. var style = document.createElement('style');
  62549. style.type = 'text/css';
  62550. 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 }";
  62551. style.innerHTML = keyFrames;
  62552. document.getElementsByTagName('head')[0].appendChild(style);
  62553. // Loading img
  62554. var imgBack = new Image();
  62555. 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";
  62556. imgBack.style.position = "absolute";
  62557. imgBack.style.left = "50%";
  62558. imgBack.style.top = "50%";
  62559. imgBack.style.marginLeft = "-60px";
  62560. imgBack.style.marginTop = "-60px";
  62561. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62562. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62563. imgBack.style.transformOrigin = "50% 50%";
  62564. imgBack.style.webkitTransformOrigin = "50% 50%";
  62565. this._loadingDiv.appendChild(imgBack);
  62566. this._resizeLoadingUI();
  62567. window.addEventListener("resize", this._resizeLoadingUI);
  62568. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62569. document.body.appendChild(this._loadingDiv);
  62570. this._loadingDiv.style.opacity = "1";
  62571. };
  62572. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62573. var _this = this;
  62574. if (!this._loadingDiv) {
  62575. return;
  62576. }
  62577. var onTransitionEnd = function () {
  62578. if (!_this._loadingDiv) {
  62579. return;
  62580. }
  62581. document.body.removeChild(_this._loadingDiv);
  62582. window.removeEventListener("resize", _this._resizeLoadingUI);
  62583. _this._loadingDiv = null;
  62584. };
  62585. this._loadingDiv.style.opacity = "0";
  62586. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62587. };
  62588. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62589. set: function (text) {
  62590. this._loadingText = text;
  62591. if (this._loadingTextDiv) {
  62592. this._loadingTextDiv.innerHTML = this._loadingText;
  62593. }
  62594. },
  62595. enumerable: true,
  62596. configurable: true
  62597. });
  62598. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62599. get: function () {
  62600. return this._loadingDivBackgroundColor;
  62601. },
  62602. set: function (color) {
  62603. this._loadingDivBackgroundColor = color;
  62604. if (!this._loadingDiv) {
  62605. return;
  62606. }
  62607. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62608. },
  62609. enumerable: true,
  62610. configurable: true
  62611. });
  62612. return DefaultLoadingScreen;
  62613. }());
  62614. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62615. })(BABYLON || (BABYLON = {}));
  62616. //# sourceMappingURL=babylon.loadingScreen.js.map
  62617. "use strict";
  62618. var BABYLON;
  62619. (function (BABYLON) {
  62620. var SceneLoaderProgressEvent = /** @class */ (function () {
  62621. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62622. this.lengthComputable = lengthComputable;
  62623. this.loaded = loaded;
  62624. this.total = total;
  62625. }
  62626. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62627. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62628. };
  62629. return SceneLoaderProgressEvent;
  62630. }());
  62631. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62632. var SceneLoader = /** @class */ (function () {
  62633. function SceneLoader() {
  62634. }
  62635. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62636. get: function () {
  62637. return 0;
  62638. },
  62639. enumerable: true,
  62640. configurable: true
  62641. });
  62642. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62643. get: function () {
  62644. return 1;
  62645. },
  62646. enumerable: true,
  62647. configurable: true
  62648. });
  62649. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62650. get: function () {
  62651. return 2;
  62652. },
  62653. enumerable: true,
  62654. configurable: true
  62655. });
  62656. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62657. get: function () {
  62658. return 3;
  62659. },
  62660. enumerable: true,
  62661. configurable: true
  62662. });
  62663. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62664. get: function () {
  62665. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62666. },
  62667. set: function (value) {
  62668. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62669. },
  62670. enumerable: true,
  62671. configurable: true
  62672. });
  62673. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62674. get: function () {
  62675. return SceneLoader._ShowLoadingScreen;
  62676. },
  62677. set: function (value) {
  62678. SceneLoader._ShowLoadingScreen = value;
  62679. },
  62680. enumerable: true,
  62681. configurable: true
  62682. });
  62683. Object.defineProperty(SceneLoader, "loggingLevel", {
  62684. get: function () {
  62685. return SceneLoader._loggingLevel;
  62686. },
  62687. set: function (value) {
  62688. SceneLoader._loggingLevel = value;
  62689. },
  62690. enumerable: true,
  62691. configurable: true
  62692. });
  62693. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62694. get: function () {
  62695. return SceneLoader._CleanBoneMatrixWeights;
  62696. },
  62697. set: function (value) {
  62698. SceneLoader._CleanBoneMatrixWeights = value;
  62699. },
  62700. enumerable: true,
  62701. configurable: true
  62702. });
  62703. SceneLoader._getDefaultPlugin = function () {
  62704. return SceneLoader._registeredPlugins[".babylon"];
  62705. };
  62706. SceneLoader._getPluginForExtension = function (extension) {
  62707. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62708. if (registeredPlugin) {
  62709. return registeredPlugin;
  62710. }
  62711. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62712. return SceneLoader._getDefaultPlugin();
  62713. };
  62714. SceneLoader._getPluginForDirectLoad = function (data) {
  62715. for (var extension in SceneLoader._registeredPlugins) {
  62716. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62717. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62718. return SceneLoader._registeredPlugins[extension];
  62719. }
  62720. }
  62721. return SceneLoader._getDefaultPlugin();
  62722. };
  62723. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62724. if (sceneFilename.name) {
  62725. sceneFilename = sceneFilename.name;
  62726. }
  62727. var queryStringPosition = sceneFilename.indexOf("?");
  62728. if (queryStringPosition !== -1) {
  62729. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62730. }
  62731. var dotPosition = sceneFilename.lastIndexOf(".");
  62732. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62733. return SceneLoader._getPluginForExtension(extension);
  62734. };
  62735. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62736. SceneLoader._getDirectLoad = function (sceneFilename) {
  62737. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62738. return sceneFilename.substr(5);
  62739. }
  62740. return null;
  62741. };
  62742. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62743. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62744. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62745. var plugin;
  62746. if (registeredPlugin.plugin.createPlugin) {
  62747. plugin = registeredPlugin.plugin.createPlugin();
  62748. }
  62749. else {
  62750. plugin = registeredPlugin.plugin;
  62751. }
  62752. var useArrayBuffer = registeredPlugin.isBinary;
  62753. var database;
  62754. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62755. var dataCallback = function (data, responseURL) {
  62756. if (scene.isDisposed) {
  62757. onError("Scene has been disposed");
  62758. return;
  62759. }
  62760. scene.database = database;
  62761. onSuccess(plugin, data, responseURL);
  62762. };
  62763. var request = null;
  62764. var pluginDisposed = false;
  62765. var onDisposeObservable = plugin.onDisposeObservable;
  62766. if (onDisposeObservable) {
  62767. onDisposeObservable.add(function () {
  62768. pluginDisposed = true;
  62769. if (request) {
  62770. request.abort();
  62771. request = null;
  62772. }
  62773. onDispose();
  62774. });
  62775. }
  62776. var manifestChecked = function () {
  62777. if (pluginDisposed) {
  62778. return;
  62779. }
  62780. var url = rootUrl + sceneFilename;
  62781. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62782. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62783. } : undefined, database, useArrayBuffer, function (request, exception) {
  62784. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62785. });
  62786. };
  62787. if (directLoad) {
  62788. dataCallback(directLoad);
  62789. return plugin;
  62790. }
  62791. if (rootUrl.indexOf("file:") === -1) {
  62792. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  62793. if (canUseOfflineSupport) {
  62794. // Also check for exceptions
  62795. var exceptionFound = false;
  62796. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  62797. var regex = _a[_i];
  62798. if (regex.test(rootUrl + sceneFilename)) {
  62799. exceptionFound = true;
  62800. break;
  62801. }
  62802. }
  62803. canUseOfflineSupport = !exceptionFound;
  62804. }
  62805. if (canUseOfflineSupport) {
  62806. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62807. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62808. }
  62809. else {
  62810. manifestChecked();
  62811. }
  62812. }
  62813. else {
  62814. var fileOrString = sceneFilename;
  62815. if (fileOrString.name) {
  62816. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62817. }
  62818. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62819. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62820. }
  62821. else {
  62822. onError("Unable to find file named " + sceneFilename);
  62823. }
  62824. }
  62825. return plugin;
  62826. };
  62827. // Public functions
  62828. SceneLoader.GetPluginForExtension = function (extension) {
  62829. return SceneLoader._getPluginForExtension(extension).plugin;
  62830. };
  62831. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62832. return !!SceneLoader._registeredPlugins[extension];
  62833. };
  62834. SceneLoader.RegisterPlugin = function (plugin) {
  62835. if (typeof plugin.extensions === "string") {
  62836. var extension = plugin.extensions;
  62837. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62838. plugin: plugin,
  62839. isBinary: false
  62840. };
  62841. }
  62842. else {
  62843. var extensions = plugin.extensions;
  62844. Object.keys(extensions).forEach(function (extension) {
  62845. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62846. plugin: plugin,
  62847. isBinary: extensions[extension].isBinary
  62848. };
  62849. });
  62850. }
  62851. };
  62852. /**
  62853. * Import meshes into a scene
  62854. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62855. * @param rootUrl a string that defines the root url for scene and resources
  62856. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62857. * @param scene the instance of BABYLON.Scene to append to
  62858. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62859. * @param onProgress a callback with a progress event for each file being loaded
  62860. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62861. * @param pluginExtension the extension used to determine the plugin
  62862. * @returns The loaded plugin
  62863. */
  62864. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62865. if (onSuccess === void 0) { onSuccess = null; }
  62866. if (onProgress === void 0) { onProgress = null; }
  62867. if (onError === void 0) { onError = null; }
  62868. if (pluginExtension === void 0) { pluginExtension = null; }
  62869. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62870. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62871. return null;
  62872. }
  62873. var loadingToken = {};
  62874. scene._addPendingData(loadingToken);
  62875. var disposeHandler = function () {
  62876. scene._removePendingData(loadingToken);
  62877. };
  62878. var errorHandler = function (message, exception) {
  62879. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62880. if (onError) {
  62881. onError(scene, errorMessage, exception);
  62882. }
  62883. else {
  62884. BABYLON.Tools.Error(errorMessage);
  62885. // should the exception be thrown?
  62886. }
  62887. disposeHandler();
  62888. };
  62889. var progressHandler = onProgress ? function (event) {
  62890. try {
  62891. onProgress(event);
  62892. }
  62893. catch (e) {
  62894. errorHandler("Error in onProgress callback", e);
  62895. }
  62896. } : undefined;
  62897. var successHandler = function (meshes, particleSystems, skeletons) {
  62898. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62899. if (onSuccess) {
  62900. try {
  62901. onSuccess(meshes, particleSystems, skeletons);
  62902. }
  62903. catch (e) {
  62904. errorHandler("Error in onSuccess callback", e);
  62905. }
  62906. }
  62907. scene._removePendingData(loadingToken);
  62908. };
  62909. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62910. if (plugin.rewriteRootURL) {
  62911. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62912. }
  62913. if (sceneFilename === "") {
  62914. if (sceneFilename === "") {
  62915. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62916. }
  62917. }
  62918. if (plugin.importMesh) {
  62919. var syncedPlugin = plugin;
  62920. var meshes = new Array();
  62921. var particleSystems = new Array();
  62922. var skeletons = new Array();
  62923. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62924. return;
  62925. }
  62926. scene.loadingPluginName = plugin.name;
  62927. successHandler(meshes, particleSystems, skeletons);
  62928. }
  62929. else {
  62930. var asyncedPlugin = plugin;
  62931. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62932. scene.loadingPluginName = plugin.name;
  62933. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62934. }).catch(function (error) {
  62935. errorHandler(error.message, error);
  62936. });
  62937. }
  62938. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62939. };
  62940. /**
  62941. * Import meshes into a scene
  62942. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62943. * @param rootUrl a string that defines the root url for scene and resources
  62944. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62945. * @param scene the instance of BABYLON.Scene to append to
  62946. * @param onProgress a callback with a progress event for each file being loaded
  62947. * @param pluginExtension the extension used to determine the plugin
  62948. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62949. */
  62950. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62951. if (onProgress === void 0) { onProgress = null; }
  62952. if (pluginExtension === void 0) { pluginExtension = null; }
  62953. return new Promise(function (resolve, reject) {
  62954. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62955. resolve({
  62956. meshes: meshes,
  62957. particleSystems: particleSystems,
  62958. skeletons: skeletons
  62959. });
  62960. }, onProgress, function (scene, message, exception) {
  62961. reject(exception || new Error(message));
  62962. });
  62963. });
  62964. };
  62965. /**
  62966. * Load a scene
  62967. * @param rootUrl a string that defines the root url for scene and resources
  62968. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62969. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62970. * @param onSuccess a callback with the scene when import succeeds
  62971. * @param onProgress a callback with a progress event for each file being loaded
  62972. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62973. * @param pluginExtension the extension used to determine the plugin
  62974. * @returns The loaded plugin
  62975. */
  62976. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62977. if (onSuccess === void 0) { onSuccess = null; }
  62978. if (onProgress === void 0) { onProgress = null; }
  62979. if (onError === void 0) { onError = null; }
  62980. if (pluginExtension === void 0) { pluginExtension = null; }
  62981. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62982. };
  62983. /**
  62984. * Load a scene
  62985. * @param rootUrl a string that defines the root url for scene and resources
  62986. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62987. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62988. * @param onProgress a callback with a progress event for each file being loaded
  62989. * @param pluginExtension the extension used to determine the plugin
  62990. * @returns The loaded scene
  62991. */
  62992. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62993. if (onProgress === void 0) { onProgress = null; }
  62994. if (pluginExtension === void 0) { pluginExtension = null; }
  62995. return new Promise(function (resolve, reject) {
  62996. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62997. resolve(scene);
  62998. }, onProgress, function (scene, message, exception) {
  62999. reject(exception || new Error(message));
  63000. }, pluginExtension);
  63001. });
  63002. };
  63003. /**
  63004. * Append a scene
  63005. * @param rootUrl a string that defines the root url for scene and resources
  63006. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63007. * @param scene is the instance of BABYLON.Scene to append to
  63008. * @param onSuccess a callback with the scene when import succeeds
  63009. * @param onProgress a callback with a progress event for each file being loaded
  63010. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63011. * @param pluginExtension the extension used to determine the plugin
  63012. * @returns The loaded plugin
  63013. */
  63014. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63015. if (onSuccess === void 0) { onSuccess = null; }
  63016. if (onProgress === void 0) { onProgress = null; }
  63017. if (onError === void 0) { onError = null; }
  63018. if (pluginExtension === void 0) { pluginExtension = null; }
  63019. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63020. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63021. return null;
  63022. }
  63023. if (SceneLoader.ShowLoadingScreen) {
  63024. scene.getEngine().displayLoadingUI();
  63025. }
  63026. var loadingToken = {};
  63027. scene._addPendingData(loadingToken);
  63028. var disposeHandler = function () {
  63029. scene._removePendingData(loadingToken);
  63030. scene.getEngine().hideLoadingUI();
  63031. };
  63032. var errorHandler = function (message, exception) {
  63033. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63034. if (onError) {
  63035. onError(scene, errorMessage, exception);
  63036. }
  63037. else {
  63038. BABYLON.Tools.Error(errorMessage);
  63039. // should the exception be thrown?
  63040. }
  63041. disposeHandler();
  63042. };
  63043. var progressHandler = onProgress ? function (event) {
  63044. try {
  63045. onProgress(event);
  63046. }
  63047. catch (e) {
  63048. errorHandler("Error in onProgress callback", e);
  63049. }
  63050. } : undefined;
  63051. var successHandler = function () {
  63052. if (onSuccess) {
  63053. try {
  63054. onSuccess(scene);
  63055. }
  63056. catch (e) {
  63057. errorHandler("Error in onSuccess callback", e);
  63058. }
  63059. }
  63060. scene._removePendingData(loadingToken);
  63061. };
  63062. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63063. if (sceneFilename === "") {
  63064. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  63065. }
  63066. if (plugin.load) {
  63067. var syncedPlugin = plugin;
  63068. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  63069. return;
  63070. }
  63071. scene.loadingPluginName = plugin.name;
  63072. successHandler();
  63073. }
  63074. else {
  63075. var asyncedPlugin = plugin;
  63076. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  63077. scene.loadingPluginName = plugin.name;
  63078. successHandler();
  63079. }).catch(function (error) {
  63080. errorHandler(error.message, error);
  63081. });
  63082. }
  63083. if (SceneLoader.ShowLoadingScreen) {
  63084. scene.executeWhenReady(function () {
  63085. scene.getEngine().hideLoadingUI();
  63086. });
  63087. }
  63088. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63089. };
  63090. /**
  63091. * Append a scene
  63092. * @param rootUrl a string that defines the root url for scene and resources
  63093. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63094. * @param scene is the instance of BABYLON.Scene to append to
  63095. * @param onProgress a callback with a progress event for each file being loaded
  63096. * @param pluginExtension the extension used to determine the plugin
  63097. * @returns The given scene
  63098. */
  63099. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63100. if (onProgress === void 0) { onProgress = null; }
  63101. if (pluginExtension === void 0) { pluginExtension = null; }
  63102. return new Promise(function (resolve, reject) {
  63103. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  63104. resolve(scene);
  63105. }, onProgress, function (scene, message, exception) {
  63106. reject(exception || new Error(message));
  63107. }, pluginExtension);
  63108. });
  63109. };
  63110. /**
  63111. * Load a scene into an asset container
  63112. * @param rootUrl a string that defines the root url for scene and resources
  63113. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63114. * @param scene is the instance of BABYLON.Scene to append to
  63115. * @param onSuccess a callback with the scene when import succeeds
  63116. * @param onProgress a callback with a progress event for each file being loaded
  63117. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63118. * @param pluginExtension the extension used to determine the plugin
  63119. * @returns The loaded plugin
  63120. */
  63121. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63122. if (onSuccess === void 0) { onSuccess = null; }
  63123. if (onProgress === void 0) { onProgress = null; }
  63124. if (onError === void 0) { onError = null; }
  63125. if (pluginExtension === void 0) { pluginExtension = null; }
  63126. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63127. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63128. return null;
  63129. }
  63130. var loadingToken = {};
  63131. scene._addPendingData(loadingToken);
  63132. var disposeHandler = function () {
  63133. scene._removePendingData(loadingToken);
  63134. };
  63135. var errorHandler = function (message, exception) {
  63136. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63137. if (onError) {
  63138. onError(scene, errorMessage, exception);
  63139. }
  63140. else {
  63141. BABYLON.Tools.Error(errorMessage);
  63142. // should the exception be thrown?
  63143. }
  63144. disposeHandler();
  63145. };
  63146. var progressHandler = onProgress ? function (event) {
  63147. try {
  63148. onProgress(event);
  63149. }
  63150. catch (e) {
  63151. errorHandler("Error in onProgress callback", e);
  63152. }
  63153. } : undefined;
  63154. var successHandler = function (assets) {
  63155. if (onSuccess) {
  63156. try {
  63157. onSuccess(assets);
  63158. }
  63159. catch (e) {
  63160. errorHandler("Error in onSuccess callback", e);
  63161. }
  63162. }
  63163. scene._removePendingData(loadingToken);
  63164. };
  63165. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63166. if (plugin.loadAssetContainer) {
  63167. var syncedPlugin = plugin;
  63168. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  63169. if (!assetContainer) {
  63170. return;
  63171. }
  63172. scene.loadingPluginName = plugin.name;
  63173. successHandler(assetContainer);
  63174. }
  63175. else if (plugin.loadAssetContainerAsync) {
  63176. var asyncedPlugin = plugin;
  63177. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  63178. scene.loadingPluginName = plugin.name;
  63179. successHandler(assetContainer);
  63180. }).catch(function (error) {
  63181. errorHandler(error.message, error);
  63182. });
  63183. }
  63184. else {
  63185. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  63186. }
  63187. if (SceneLoader.ShowLoadingScreen) {
  63188. scene.executeWhenReady(function () {
  63189. scene.getEngine().hideLoadingUI();
  63190. });
  63191. }
  63192. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63193. };
  63194. /**
  63195. * Load a scene into an asset container
  63196. * @param rootUrl a string that defines the root url for scene and resources
  63197. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63198. * @param scene is the instance of BABYLON.Scene to append to
  63199. * @param onProgress a callback with a progress event for each file being loaded
  63200. * @param pluginExtension the extension used to determine the plugin
  63201. * @returns The loaded asset container
  63202. */
  63203. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63204. if (onProgress === void 0) { onProgress = null; }
  63205. if (pluginExtension === void 0) { pluginExtension = null; }
  63206. return new Promise(function (resolve, reject) {
  63207. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  63208. resolve(assetContainer);
  63209. }, onProgress, function (scene, message, exception) {
  63210. reject(exception || new Error(message));
  63211. }, pluginExtension);
  63212. });
  63213. };
  63214. // Flags
  63215. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  63216. SceneLoader._ShowLoadingScreen = true;
  63217. SceneLoader._CleanBoneMatrixWeights = false;
  63218. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  63219. // Members
  63220. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  63221. SceneLoader._registeredPlugins = {};
  63222. return SceneLoader;
  63223. }());
  63224. BABYLON.SceneLoader = SceneLoader;
  63225. ;
  63226. })(BABYLON || (BABYLON = {}));
  63227. //# sourceMappingURL=babylon.sceneLoader.js.map
  63228. "use strict";
  63229. var BABYLON;
  63230. (function (BABYLON) {
  63231. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  63232. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63233. var parsedMaterial = parsedData.materials[index];
  63234. if (parsedMaterial.id === id) {
  63235. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63236. }
  63237. }
  63238. return null;
  63239. };
  63240. var isDescendantOf = function (mesh, names, hierarchyIds) {
  63241. for (var i in names) {
  63242. if (mesh.name === names[i]) {
  63243. hierarchyIds.push(mesh.id);
  63244. return true;
  63245. }
  63246. }
  63247. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  63248. hierarchyIds.push(mesh.id);
  63249. return true;
  63250. }
  63251. return false;
  63252. };
  63253. var logOperation = function (operation, producer) {
  63254. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  63255. };
  63256. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  63257. if (addToScene === void 0) { addToScene = false; }
  63258. var container = new BABYLON.AssetContainer(scene);
  63259. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63260. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63261. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63262. // and avoid problems with multiple concurrent .babylon loads.
  63263. var log = "importScene has failed JSON parse";
  63264. try {
  63265. var parsedData = JSON.parse(data);
  63266. log = "";
  63267. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63268. var index;
  63269. var cache;
  63270. // Lights
  63271. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  63272. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  63273. var parsedLight = parsedData.lights[index];
  63274. var light = BABYLON.Light.Parse(parsedLight, scene);
  63275. if (light) {
  63276. container.lights.push(light);
  63277. log += (index === 0 ? "\n\tLights:" : "");
  63278. log += "\n\t\t" + light.toString(fullDetails);
  63279. }
  63280. }
  63281. }
  63282. // Animations
  63283. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  63284. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  63285. var parsedAnimation = parsedData.animations[index];
  63286. var animation = BABYLON.Animation.Parse(parsedAnimation);
  63287. scene.animations.push(animation);
  63288. container.animations.push(animation);
  63289. log += (index === 0 ? "\n\tAnimations:" : "");
  63290. log += "\n\t\t" + animation.toString(fullDetails);
  63291. }
  63292. }
  63293. // Materials
  63294. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  63295. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63296. var parsedMaterial = parsedData.materials[index];
  63297. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63298. container.materials.push(mat);
  63299. log += (index === 0 ? "\n\tMaterials:" : "");
  63300. log += "\n\t\t" + mat.toString(fullDetails);
  63301. }
  63302. }
  63303. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63304. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  63305. var parsedMultiMaterial = parsedData.multiMaterials[index];
  63306. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63307. container.multiMaterials.push(mmat);
  63308. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63309. log += "\n\t\t" + mmat.toString(fullDetails);
  63310. }
  63311. }
  63312. // Morph targets
  63313. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63314. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63315. var managerData = _a[_i];
  63316. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63317. }
  63318. }
  63319. // Skeletons
  63320. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63321. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63322. var parsedSkeleton = parsedData.skeletons[index];
  63323. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63324. container.skeletons.push(skeleton);
  63325. log += (index === 0 ? "\n\tSkeletons:" : "");
  63326. log += "\n\t\t" + skeleton.toString(fullDetails);
  63327. }
  63328. }
  63329. // Geometries
  63330. var geometries = parsedData.geometries;
  63331. if (geometries !== undefined && geometries !== null) {
  63332. var addedGeometry = new Array();
  63333. // Boxes
  63334. var boxes = geometries.boxes;
  63335. if (boxes !== undefined && boxes !== null) {
  63336. for (index = 0, cache = boxes.length; index < cache; index++) {
  63337. var parsedBox = boxes[index];
  63338. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63339. }
  63340. }
  63341. // Spheres
  63342. var spheres = geometries.spheres;
  63343. if (spheres !== undefined && spheres !== null) {
  63344. for (index = 0, cache = spheres.length; index < cache; index++) {
  63345. var parsedSphere = spheres[index];
  63346. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63347. }
  63348. }
  63349. // Cylinders
  63350. var cylinders = geometries.cylinders;
  63351. if (cylinders !== undefined && cylinders !== null) {
  63352. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63353. var parsedCylinder = cylinders[index];
  63354. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63355. }
  63356. }
  63357. // Toruses
  63358. var toruses = geometries.toruses;
  63359. if (toruses !== undefined && toruses !== null) {
  63360. for (index = 0, cache = toruses.length; index < cache; index++) {
  63361. var parsedTorus = toruses[index];
  63362. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63363. }
  63364. }
  63365. // Grounds
  63366. var grounds = geometries.grounds;
  63367. if (grounds !== undefined && grounds !== null) {
  63368. for (index = 0, cache = grounds.length; index < cache; index++) {
  63369. var parsedGround = grounds[index];
  63370. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63371. }
  63372. }
  63373. // Planes
  63374. var planes = geometries.planes;
  63375. if (planes !== undefined && planes !== null) {
  63376. for (index = 0, cache = planes.length; index < cache; index++) {
  63377. var parsedPlane = planes[index];
  63378. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63379. }
  63380. }
  63381. // TorusKnots
  63382. var torusKnots = geometries.torusKnots;
  63383. if (torusKnots !== undefined && torusKnots !== null) {
  63384. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63385. var parsedTorusKnot = torusKnots[index];
  63386. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63387. }
  63388. }
  63389. // VertexData
  63390. var vertexData = geometries.vertexData;
  63391. if (vertexData !== undefined && vertexData !== null) {
  63392. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63393. var parsedVertexData = vertexData[index];
  63394. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63395. }
  63396. }
  63397. addedGeometry.forEach(function (g) {
  63398. if (g) {
  63399. container.geometries.push(g);
  63400. }
  63401. });
  63402. }
  63403. // Transform nodes
  63404. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63405. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63406. var parsedTransformNode = parsedData.transformNodes[index];
  63407. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63408. container.transformNodes.push(node);
  63409. }
  63410. }
  63411. // Meshes
  63412. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63413. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63414. var parsedMesh = parsedData.meshes[index];
  63415. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63416. container.meshes.push(mesh);
  63417. log += (index === 0 ? "\n\tMeshes:" : "");
  63418. log += "\n\t\t" + mesh.toString(fullDetails);
  63419. }
  63420. }
  63421. // Cameras
  63422. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63423. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63424. var parsedCamera = parsedData.cameras[index];
  63425. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63426. container.cameras.push(camera);
  63427. log += (index === 0 ? "\n\tCameras:" : "");
  63428. log += "\n\t\t" + camera.toString(fullDetails);
  63429. }
  63430. }
  63431. // Browsing all the graph to connect the dots
  63432. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63433. var camera = scene.cameras[index];
  63434. if (camera._waitingParentId) {
  63435. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63436. camera._waitingParentId = null;
  63437. }
  63438. }
  63439. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63440. var light_1 = scene.lights[index];
  63441. if (light_1 && light_1._waitingParentId) {
  63442. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63443. light_1._waitingParentId = null;
  63444. }
  63445. }
  63446. // Sounds
  63447. // TODO: add sound
  63448. var loadedSounds = [];
  63449. var loadedSound;
  63450. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63451. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63452. var parsedSound = parsedData.sounds[index];
  63453. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63454. if (!parsedSound.url)
  63455. parsedSound.url = parsedSound.name;
  63456. if (!loadedSounds[parsedSound.url]) {
  63457. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63458. loadedSounds[parsedSound.url] = loadedSound;
  63459. container.sounds.push(loadedSound);
  63460. }
  63461. else {
  63462. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63463. }
  63464. }
  63465. else {
  63466. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63467. }
  63468. }
  63469. }
  63470. loadedSounds = [];
  63471. // Connect parents & children and parse actions
  63472. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63473. var transformNode = scene.transformNodes[index];
  63474. if (transformNode._waitingParentId) {
  63475. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63476. transformNode._waitingParentId = null;
  63477. }
  63478. }
  63479. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63480. var mesh = scene.meshes[index];
  63481. if (mesh._waitingParentId) {
  63482. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63483. mesh._waitingParentId = null;
  63484. }
  63485. if (mesh._waitingActions) {
  63486. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63487. mesh._waitingActions = null;
  63488. }
  63489. }
  63490. // freeze world matrix application
  63491. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63492. var currentMesh = scene.meshes[index];
  63493. if (currentMesh._waitingFreezeWorldMatrix) {
  63494. currentMesh.freezeWorldMatrix();
  63495. currentMesh._waitingFreezeWorldMatrix = null;
  63496. }
  63497. else {
  63498. currentMesh.computeWorldMatrix(true);
  63499. }
  63500. }
  63501. // Particles Systems
  63502. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63503. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63504. var parsedParticleSystem = parsedData.particleSystems[index];
  63505. if (parsedParticleSystem.activeParticleCount) {
  63506. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63507. container.particleSystems.push(ps);
  63508. }
  63509. else {
  63510. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63511. container.particleSystems.push(ps);
  63512. }
  63513. }
  63514. }
  63515. // Lens flares
  63516. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63517. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63518. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63519. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63520. container.lensFlareSystems.push(lf);
  63521. }
  63522. }
  63523. // Shadows
  63524. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63525. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63526. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63527. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63528. container.shadowGenerators.push(sg);
  63529. }
  63530. }
  63531. // Lights exclusions / inclusions
  63532. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63533. var light_2 = scene.lights[index];
  63534. // Excluded check
  63535. if (light_2._excludedMeshesIds.length > 0) {
  63536. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63537. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63538. if (excludedMesh) {
  63539. light_2.excludedMeshes.push(excludedMesh);
  63540. }
  63541. }
  63542. light_2._excludedMeshesIds = [];
  63543. }
  63544. // Included check
  63545. if (light_2._includedOnlyMeshesIds.length > 0) {
  63546. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63547. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63548. if (includedOnlyMesh) {
  63549. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63550. }
  63551. }
  63552. light_2._includedOnlyMeshesIds = [];
  63553. }
  63554. }
  63555. // Actions (scene)
  63556. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63557. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63558. }
  63559. if (!addToScene) {
  63560. container.removeAllFromScene();
  63561. }
  63562. }
  63563. catch (err) {
  63564. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63565. if (onError) {
  63566. onError(msg, err);
  63567. }
  63568. else {
  63569. BABYLON.Tools.Log(msg);
  63570. throw err;
  63571. }
  63572. }
  63573. finally {
  63574. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63575. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63576. }
  63577. }
  63578. return container;
  63579. };
  63580. BABYLON.SceneLoader.RegisterPlugin({
  63581. name: "babylon.js",
  63582. extensions: ".babylon",
  63583. canDirectLoad: function (data) {
  63584. if (data.indexOf("babylon") !== -1) {
  63585. return true;
  63586. }
  63587. return false;
  63588. },
  63589. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63590. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63591. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63592. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63593. // and avoid problems with multiple concurrent .babylon loads.
  63594. var log = "importMesh has failed JSON parse";
  63595. try {
  63596. var parsedData = JSON.parse(data);
  63597. log = "";
  63598. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63599. if (!meshesNames) {
  63600. meshesNames = null;
  63601. }
  63602. else if (!Array.isArray(meshesNames)) {
  63603. meshesNames = [meshesNames];
  63604. }
  63605. var hierarchyIds = new Array();
  63606. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63607. var loadedSkeletonsIds = [];
  63608. var loadedMaterialsIds = [];
  63609. var index;
  63610. var cache;
  63611. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63612. var parsedMesh = parsedData.meshes[index];
  63613. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63614. if (meshesNames !== null) {
  63615. // Remove found mesh name from list.
  63616. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63617. }
  63618. //Geometry?
  63619. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63620. //does the file contain geometries?
  63621. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63622. //find the correct geometry and add it to the scene
  63623. var found = false;
  63624. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63625. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63626. return;
  63627. }
  63628. else {
  63629. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63630. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63631. switch (geometryType) {
  63632. case "boxes":
  63633. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63634. break;
  63635. case "spheres":
  63636. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63637. break;
  63638. case "cylinders":
  63639. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63640. break;
  63641. case "toruses":
  63642. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63643. break;
  63644. case "grounds":
  63645. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63646. break;
  63647. case "planes":
  63648. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63649. break;
  63650. case "torusKnots":
  63651. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63652. break;
  63653. case "vertexData":
  63654. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63655. break;
  63656. }
  63657. found = true;
  63658. }
  63659. });
  63660. }
  63661. });
  63662. if (found === false) {
  63663. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63664. }
  63665. }
  63666. }
  63667. // Material ?
  63668. if (parsedMesh.materialId) {
  63669. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63670. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63671. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63672. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63673. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63674. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63675. var subMatId = parsedMultiMaterial.materials[matIndex];
  63676. loadedMaterialsIds.push(subMatId);
  63677. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63678. if (mat) {
  63679. log += "\n\tMaterial " + mat.toString(fullDetails);
  63680. }
  63681. }
  63682. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63683. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63684. if (mmat) {
  63685. materialFound = true;
  63686. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63687. }
  63688. break;
  63689. }
  63690. }
  63691. }
  63692. if (materialFound === false) {
  63693. loadedMaterialsIds.push(parsedMesh.materialId);
  63694. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63695. if (!mat) {
  63696. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63697. }
  63698. else {
  63699. log += "\n\tMaterial " + mat.toString(fullDetails);
  63700. }
  63701. }
  63702. }
  63703. // Skeleton ?
  63704. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63705. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63706. if (skeletonAlreadyLoaded === false) {
  63707. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63708. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63709. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63710. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63711. skeletons.push(skeleton);
  63712. loadedSkeletonsIds.push(parsedSkeleton.id);
  63713. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63714. }
  63715. }
  63716. }
  63717. }
  63718. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63719. meshes.push(mesh);
  63720. log += "\n\tMesh " + mesh.toString(fullDetails);
  63721. }
  63722. }
  63723. // Connecting parents
  63724. var currentMesh;
  63725. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63726. currentMesh = scene.meshes[index];
  63727. if (currentMesh._waitingParentId) {
  63728. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63729. currentMesh._waitingParentId = null;
  63730. }
  63731. }
  63732. // freeze and compute world matrix application
  63733. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63734. currentMesh = scene.meshes[index];
  63735. if (currentMesh._waitingFreezeWorldMatrix) {
  63736. currentMesh.freezeWorldMatrix();
  63737. currentMesh._waitingFreezeWorldMatrix = null;
  63738. }
  63739. else {
  63740. currentMesh.computeWorldMatrix(true);
  63741. }
  63742. }
  63743. }
  63744. // Particles
  63745. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63746. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63747. var parsedParticleSystem = parsedData.particleSystems[index];
  63748. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63749. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63750. }
  63751. }
  63752. }
  63753. return true;
  63754. }
  63755. catch (err) {
  63756. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63757. if (onError) {
  63758. onError(msg, err);
  63759. }
  63760. else {
  63761. BABYLON.Tools.Log(msg);
  63762. throw err;
  63763. }
  63764. }
  63765. finally {
  63766. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63767. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63768. }
  63769. }
  63770. return false;
  63771. },
  63772. load: function (scene, data, rootUrl, onError) {
  63773. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63774. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63775. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63776. // and avoid problems with multiple concurrent .babylon loads.
  63777. var log = "importScene has failed JSON parse";
  63778. try {
  63779. var parsedData = JSON.parse(data);
  63780. log = "";
  63781. // Scene
  63782. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63783. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63784. }
  63785. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63786. scene.autoClear = parsedData.autoClear;
  63787. }
  63788. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63789. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63790. }
  63791. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63792. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63793. }
  63794. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63795. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63796. }
  63797. // Fog
  63798. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63799. scene.fogMode = parsedData.fogMode;
  63800. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63801. scene.fogStart = parsedData.fogStart;
  63802. scene.fogEnd = parsedData.fogEnd;
  63803. scene.fogDensity = parsedData.fogDensity;
  63804. log += "\tFog mode for scene: ";
  63805. switch (scene.fogMode) {
  63806. // getters not compiling, so using hardcoded
  63807. case 1:
  63808. log += "exp\n";
  63809. break;
  63810. case 2:
  63811. log += "exp2\n";
  63812. break;
  63813. case 3:
  63814. log += "linear\n";
  63815. break;
  63816. }
  63817. }
  63818. //Physics
  63819. if (parsedData.physicsEnabled) {
  63820. var physicsPlugin;
  63821. if (parsedData.physicsEngine === "cannon") {
  63822. physicsPlugin = new BABYLON.CannonJSPlugin();
  63823. }
  63824. else if (parsedData.physicsEngine === "oimo") {
  63825. physicsPlugin = new BABYLON.OimoJSPlugin();
  63826. }
  63827. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63828. //else - default engine, which is currently oimo
  63829. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63830. scene.enablePhysics(physicsGravity, physicsPlugin);
  63831. }
  63832. // Metadata
  63833. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63834. scene.metadata = parsedData.metadata;
  63835. }
  63836. //collisions, if defined. otherwise, default is true
  63837. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63838. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63839. }
  63840. scene.workerCollisions = !!parsedData.workerCollisions;
  63841. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63842. if (!container) {
  63843. return false;
  63844. }
  63845. if (parsedData.autoAnimate) {
  63846. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63847. }
  63848. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63849. scene.setActiveCameraByID(parsedData.activeCameraID);
  63850. }
  63851. // Environment texture
  63852. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63853. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63854. if (parsedData.createDefaultSkybox === true) {
  63855. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63856. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63857. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63858. }
  63859. }
  63860. // Finish
  63861. return true;
  63862. }
  63863. catch (err) {
  63864. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63865. if (onError) {
  63866. onError(msg, err);
  63867. }
  63868. else {
  63869. BABYLON.Tools.Log(msg);
  63870. throw err;
  63871. }
  63872. }
  63873. finally {
  63874. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63875. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63876. }
  63877. }
  63878. return false;
  63879. },
  63880. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63881. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63882. return container;
  63883. }
  63884. });
  63885. })(BABYLON || (BABYLON = {}));
  63886. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63887. "use strict";
  63888. var BABYLON;
  63889. (function (BABYLON) {
  63890. var FilesInput = /** @class */ (function () {
  63891. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63892. this.onProcessFileCallback = function () { return true; };
  63893. this._engine = engine;
  63894. this._currentScene = scene;
  63895. this._sceneLoadedCallback = sceneLoadedCallback;
  63896. this._progressCallback = progressCallback;
  63897. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63898. this._textureLoadingCallback = textureLoadingCallback;
  63899. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63900. this._onReloadCallback = onReloadCallback;
  63901. this._errorCallback = errorCallback;
  63902. }
  63903. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63904. var _this = this;
  63905. if (elementToMonitor) {
  63906. this._elementToMonitor = elementToMonitor;
  63907. this._dragEnterHandler = function (e) { _this.drag(e); };
  63908. this._dragOverHandler = function (e) { _this.drag(e); };
  63909. this._dropHandler = function (e) { _this.drop(e); };
  63910. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63911. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63912. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63913. }
  63914. };
  63915. FilesInput.prototype.dispose = function () {
  63916. if (!this._elementToMonitor) {
  63917. return;
  63918. }
  63919. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63920. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63921. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63922. };
  63923. FilesInput.prototype.renderFunction = function () {
  63924. if (this._additionalRenderLoopLogicCallback) {
  63925. this._additionalRenderLoopLogicCallback();
  63926. }
  63927. if (this._currentScene) {
  63928. if (this._textureLoadingCallback) {
  63929. var remaining = this._currentScene.getWaitingItemsCount();
  63930. if (remaining > 0) {
  63931. this._textureLoadingCallback(remaining);
  63932. }
  63933. }
  63934. this._currentScene.render();
  63935. }
  63936. };
  63937. FilesInput.prototype.drag = function (e) {
  63938. e.stopPropagation();
  63939. e.preventDefault();
  63940. };
  63941. FilesInput.prototype.drop = function (eventDrop) {
  63942. eventDrop.stopPropagation();
  63943. eventDrop.preventDefault();
  63944. this.loadFiles(eventDrop);
  63945. };
  63946. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63947. var _this = this;
  63948. var reader = folder.createReader();
  63949. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63950. reader.readEntries(function (entries) {
  63951. remaining.count += entries.length;
  63952. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63953. var entry = entries_1[_i];
  63954. if (entry.isFile) {
  63955. entry.file(function (file) {
  63956. file.correctName = relativePath + file.name;
  63957. files.push(file);
  63958. if (--remaining.count === 0) {
  63959. callback();
  63960. }
  63961. });
  63962. }
  63963. else if (entry.isDirectory) {
  63964. _this._traverseFolder(entry, files, remaining, callback);
  63965. }
  63966. }
  63967. if (--remaining.count) {
  63968. callback();
  63969. }
  63970. });
  63971. };
  63972. FilesInput.prototype._processFiles = function (files) {
  63973. for (var i = 0; i < files.length; i++) {
  63974. var name = files[i].correctName.toLowerCase();
  63975. var extension = name.split('.').pop();
  63976. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63977. continue;
  63978. }
  63979. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63980. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63981. this._sceneFileToLoad = files[i];
  63982. }
  63983. else {
  63984. FilesInput.FilesToLoad[name] = files[i];
  63985. }
  63986. }
  63987. };
  63988. FilesInput.prototype.loadFiles = function (event) {
  63989. var _this = this;
  63990. if (this._startingProcessingFilesCallback)
  63991. this._startingProcessingFilesCallback();
  63992. // Handling data transfer via drag'n'drop
  63993. if (event && event.dataTransfer && event.dataTransfer.files) {
  63994. this._filesToLoad = event.dataTransfer.files;
  63995. }
  63996. // Handling files from input files
  63997. if (event && event.target && event.target.files) {
  63998. this._filesToLoad = event.target.files;
  63999. }
  64000. if (this._filesToLoad && this._filesToLoad.length > 0) {
  64001. var files_1 = new Array();
  64002. var folders = [];
  64003. var items = event.dataTransfer ? event.dataTransfer.items : null;
  64004. for (var i = 0; i < this._filesToLoad.length; i++) {
  64005. var fileToLoad = this._filesToLoad[i];
  64006. var name_1 = fileToLoad.name.toLowerCase();
  64007. var entry = void 0;
  64008. fileToLoad.correctName = name_1;
  64009. if (items) {
  64010. var item = items[i];
  64011. if (item.getAsEntry) {
  64012. entry = item.getAsEntry();
  64013. }
  64014. else if (item.webkitGetAsEntry) {
  64015. entry = item.webkitGetAsEntry();
  64016. }
  64017. }
  64018. if (!entry) {
  64019. files_1.push(fileToLoad);
  64020. }
  64021. else {
  64022. if (entry.isDirectory) {
  64023. folders.push(entry);
  64024. }
  64025. else {
  64026. files_1.push(fileToLoad);
  64027. }
  64028. }
  64029. }
  64030. if (folders.length === 0) {
  64031. this._processFiles(files_1);
  64032. this._processReload();
  64033. }
  64034. else {
  64035. var remaining = { count: folders.length };
  64036. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  64037. var folder = folders_1[_i];
  64038. this._traverseFolder(folder, files_1, remaining, function () {
  64039. _this._processFiles(files_1);
  64040. if (remaining.count === 0) {
  64041. _this._processReload();
  64042. }
  64043. });
  64044. }
  64045. }
  64046. }
  64047. };
  64048. FilesInput.prototype._processReload = function () {
  64049. if (this._onReloadCallback) {
  64050. this._onReloadCallback(this._sceneFileToLoad);
  64051. }
  64052. else {
  64053. this.reload();
  64054. }
  64055. };
  64056. FilesInput.prototype.reload = function () {
  64057. var _this = this;
  64058. // If a scene file has been provided
  64059. if (this._sceneFileToLoad) {
  64060. if (this._currentScene) {
  64061. if (BABYLON.Tools.errorsCount > 0) {
  64062. BABYLON.Tools.ClearLogCache();
  64063. }
  64064. this._engine.stopRenderLoop();
  64065. this._currentScene.dispose();
  64066. }
  64067. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  64068. if (_this._progressCallback) {
  64069. _this._progressCallback(progress);
  64070. }
  64071. }).then(function (scene) {
  64072. _this._currentScene = scene;
  64073. if (_this._sceneLoadedCallback) {
  64074. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  64075. }
  64076. // Wait for textures and shaders to be ready
  64077. _this._currentScene.executeWhenReady(function () {
  64078. _this._engine.runRenderLoop(function () {
  64079. _this.renderFunction();
  64080. });
  64081. });
  64082. }).catch(function (error) {
  64083. if (_this._errorCallback) {
  64084. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  64085. }
  64086. });
  64087. }
  64088. else {
  64089. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  64090. }
  64091. };
  64092. FilesInput.FilesToLoad = {};
  64093. return FilesInput;
  64094. }());
  64095. BABYLON.FilesInput = FilesInput;
  64096. })(BABYLON || (BABYLON = {}));
  64097. //# sourceMappingURL=babylon.filesInput.js.map
  64098. "use strict";
  64099. var BABYLON;
  64100. (function (BABYLON) {
  64101. /**
  64102. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64103. * The underlying implementation relies on an associative array to ensure the best performances.
  64104. * The value can be anything including 'null' but except 'undefined'
  64105. */
  64106. var StringDictionary = /** @class */ (function () {
  64107. function StringDictionary() {
  64108. this._count = 0;
  64109. this._data = {};
  64110. }
  64111. /**
  64112. * This will clear this dictionary and copy the content from the 'source' one.
  64113. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64114. * @param source the dictionary to take the content from and copy to this dictionary
  64115. */
  64116. StringDictionary.prototype.copyFrom = function (source) {
  64117. var _this = this;
  64118. this.clear();
  64119. source.forEach(function (t, v) { return _this.add(t, v); });
  64120. };
  64121. /**
  64122. * Get a value based from its key
  64123. * @param key the given key to get the matching value from
  64124. * @return the value if found, otherwise undefined is returned
  64125. */
  64126. StringDictionary.prototype.get = function (key) {
  64127. var val = this._data[key];
  64128. if (val !== undefined) {
  64129. return val;
  64130. }
  64131. return undefined;
  64132. };
  64133. /**
  64134. * Get a value from its key or add it if it doesn't exist.
  64135. * This method will ensure you that a given key/data will be present in the dictionary.
  64136. * @param key the given key to get the matching value from
  64137. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64138. * The factory will only be invoked if there's no data for the given key.
  64139. * @return the value corresponding to the key.
  64140. */
  64141. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64142. var val = this.get(key);
  64143. if (val !== undefined) {
  64144. return val;
  64145. }
  64146. val = factory(key);
  64147. if (val) {
  64148. this.add(key, val);
  64149. }
  64150. return val;
  64151. };
  64152. /**
  64153. * Get a value from its key if present in the dictionary otherwise add it
  64154. * @param key the key to get the value from
  64155. * @param val if there's no such key/value pair in the dictionary add it with this value
  64156. * @return the value corresponding to the key
  64157. */
  64158. StringDictionary.prototype.getOrAdd = function (key, val) {
  64159. var curVal = this.get(key);
  64160. if (curVal !== undefined) {
  64161. return curVal;
  64162. }
  64163. this.add(key, val);
  64164. return val;
  64165. };
  64166. /**
  64167. * Check if there's a given key in the dictionary
  64168. * @param key the key to check for
  64169. * @return true if the key is present, false otherwise
  64170. */
  64171. StringDictionary.prototype.contains = function (key) {
  64172. return this._data[key] !== undefined;
  64173. };
  64174. /**
  64175. * Add a new key and its corresponding value
  64176. * @param key the key to add
  64177. * @param value the value corresponding to the key
  64178. * @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
  64179. */
  64180. StringDictionary.prototype.add = function (key, value) {
  64181. if (this._data[key] !== undefined) {
  64182. return false;
  64183. }
  64184. this._data[key] = value;
  64185. ++this._count;
  64186. return true;
  64187. };
  64188. StringDictionary.prototype.set = function (key, value) {
  64189. if (this._data[key] === undefined) {
  64190. return false;
  64191. }
  64192. this._data[key] = value;
  64193. return true;
  64194. };
  64195. /**
  64196. * Get the element of the given key and remove it from the dictionary
  64197. * @param key
  64198. */
  64199. StringDictionary.prototype.getAndRemove = function (key) {
  64200. var val = this.get(key);
  64201. if (val !== undefined) {
  64202. delete this._data[key];
  64203. --this._count;
  64204. return val;
  64205. }
  64206. return null;
  64207. };
  64208. /**
  64209. * Remove a key/value from the dictionary.
  64210. * @param key the key to remove
  64211. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64212. */
  64213. StringDictionary.prototype.remove = function (key) {
  64214. if (this.contains(key)) {
  64215. delete this._data[key];
  64216. --this._count;
  64217. return true;
  64218. }
  64219. return false;
  64220. };
  64221. /**
  64222. * Clear the whole content of the dictionary
  64223. */
  64224. StringDictionary.prototype.clear = function () {
  64225. this._data = {};
  64226. this._count = 0;
  64227. };
  64228. Object.defineProperty(StringDictionary.prototype, "count", {
  64229. get: function () {
  64230. return this._count;
  64231. },
  64232. enumerable: true,
  64233. configurable: true
  64234. });
  64235. /**
  64236. * Execute a callback on each key/val of the dictionary.
  64237. * Note that you can remove any element in this dictionary in the callback implementation
  64238. * @param callback the callback to execute on a given key/value pair
  64239. */
  64240. StringDictionary.prototype.forEach = function (callback) {
  64241. for (var cur in this._data) {
  64242. var val = this._data[cur];
  64243. callback(cur, val);
  64244. }
  64245. };
  64246. /**
  64247. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64248. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64249. * Note that you can remove any element in this dictionary in the callback implementation
  64250. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64251. */
  64252. StringDictionary.prototype.first = function (callback) {
  64253. for (var cur in this._data) {
  64254. var val = this._data[cur];
  64255. var res = callback(cur, val);
  64256. if (res) {
  64257. return res;
  64258. }
  64259. }
  64260. return null;
  64261. };
  64262. return StringDictionary;
  64263. }());
  64264. BABYLON.StringDictionary = StringDictionary;
  64265. })(BABYLON || (BABYLON = {}));
  64266. //# sourceMappingURL=babylon.stringDictionary.js.map
  64267. "use strict";
  64268. var BABYLON;
  64269. (function (BABYLON) {
  64270. var Tags = /** @class */ (function () {
  64271. function Tags() {
  64272. }
  64273. Tags.EnableFor = function (obj) {
  64274. obj._tags = obj._tags || {};
  64275. obj.hasTags = function () {
  64276. return Tags.HasTags(obj);
  64277. };
  64278. obj.addTags = function (tagsString) {
  64279. return Tags.AddTagsTo(obj, tagsString);
  64280. };
  64281. obj.removeTags = function (tagsString) {
  64282. return Tags.RemoveTagsFrom(obj, tagsString);
  64283. };
  64284. obj.matchesTagsQuery = function (tagsQuery) {
  64285. return Tags.MatchesQuery(obj, tagsQuery);
  64286. };
  64287. };
  64288. Tags.DisableFor = function (obj) {
  64289. delete obj._tags;
  64290. delete obj.hasTags;
  64291. delete obj.addTags;
  64292. delete obj.removeTags;
  64293. delete obj.matchesTagsQuery;
  64294. };
  64295. Tags.HasTags = function (obj) {
  64296. if (!obj._tags) {
  64297. return false;
  64298. }
  64299. return !BABYLON.Tools.IsEmpty(obj._tags);
  64300. };
  64301. Tags.GetTags = function (obj, asString) {
  64302. if (asString === void 0) { asString = true; }
  64303. if (!obj._tags) {
  64304. return null;
  64305. }
  64306. if (asString) {
  64307. var tagsArray = [];
  64308. for (var tag in obj._tags) {
  64309. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64310. tagsArray.push(tag);
  64311. }
  64312. }
  64313. return tagsArray.join(" ");
  64314. }
  64315. else {
  64316. return obj._tags;
  64317. }
  64318. };
  64319. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64320. // a tag cannot start with '||', '&&', and '!'
  64321. // it cannot contain whitespaces
  64322. Tags.AddTagsTo = function (obj, tagsString) {
  64323. if (!tagsString) {
  64324. return;
  64325. }
  64326. if (typeof tagsString !== "string") {
  64327. return;
  64328. }
  64329. var tags = tagsString.split(" ");
  64330. tags.forEach(function (tag, index, array) {
  64331. Tags._AddTagTo(obj, tag);
  64332. });
  64333. };
  64334. Tags._AddTagTo = function (obj, tag) {
  64335. tag = tag.trim();
  64336. if (tag === "" || tag === "true" || tag === "false") {
  64337. return;
  64338. }
  64339. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64340. return;
  64341. }
  64342. Tags.EnableFor(obj);
  64343. obj._tags[tag] = true;
  64344. };
  64345. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64346. if (!Tags.HasTags(obj)) {
  64347. return;
  64348. }
  64349. var tags = tagsString.split(" ");
  64350. for (var t in tags) {
  64351. Tags._RemoveTagFrom(obj, tags[t]);
  64352. }
  64353. };
  64354. Tags._RemoveTagFrom = function (obj, tag) {
  64355. delete obj._tags[tag];
  64356. };
  64357. Tags.MatchesQuery = function (obj, tagsQuery) {
  64358. if (tagsQuery === undefined) {
  64359. return true;
  64360. }
  64361. if (tagsQuery === "") {
  64362. return Tags.HasTags(obj);
  64363. }
  64364. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64365. };
  64366. return Tags;
  64367. }());
  64368. BABYLON.Tags = Tags;
  64369. })(BABYLON || (BABYLON = {}));
  64370. //# sourceMappingURL=babylon.tags.js.map
  64371. "use strict";
  64372. var BABYLON;
  64373. (function (BABYLON) {
  64374. var AndOrNotEvaluator = /** @class */ (function () {
  64375. function AndOrNotEvaluator() {
  64376. }
  64377. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64378. if (!query.match(/\([^\(\)]*\)/g)) {
  64379. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64380. }
  64381. else {
  64382. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64383. // remove parenthesis
  64384. r = r.slice(1, r.length - 1);
  64385. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64386. });
  64387. }
  64388. if (query === "true") {
  64389. return true;
  64390. }
  64391. if (query === "false") {
  64392. return false;
  64393. }
  64394. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64395. };
  64396. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64397. evaluateCallback = evaluateCallback || (function (r) {
  64398. return r === "true" ? true : false;
  64399. });
  64400. var result;
  64401. var or = parenthesisContent.split("||");
  64402. for (var i in or) {
  64403. if (or.hasOwnProperty(i)) {
  64404. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64405. var and = ori.split("&&");
  64406. if (and.length > 1) {
  64407. for (var j = 0; j < and.length; ++j) {
  64408. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64409. if (andj !== "true" && andj !== "false") {
  64410. if (andj[0] === "!") {
  64411. result = !evaluateCallback(andj.substring(1));
  64412. }
  64413. else {
  64414. result = evaluateCallback(andj);
  64415. }
  64416. }
  64417. else {
  64418. result = andj === "true" ? true : false;
  64419. }
  64420. if (!result) {
  64421. ori = "false";
  64422. break;
  64423. }
  64424. }
  64425. }
  64426. if (result || ori === "true") {
  64427. result = true;
  64428. break;
  64429. }
  64430. // result equals false (or undefined)
  64431. if (ori !== "true" && ori !== "false") {
  64432. if (ori[0] === "!") {
  64433. result = !evaluateCallback(ori.substring(1));
  64434. }
  64435. else {
  64436. result = evaluateCallback(ori);
  64437. }
  64438. }
  64439. else {
  64440. result = ori === "true" ? true : false;
  64441. }
  64442. }
  64443. }
  64444. // the whole parenthesis scope is replaced by 'true' or 'false'
  64445. return result ? "true" : "false";
  64446. };
  64447. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64448. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64449. // remove whitespaces
  64450. r = r.replace(/[\s]/g, function () { return ""; });
  64451. return r.length % 2 ? "!" : "";
  64452. });
  64453. booleanString = booleanString.trim();
  64454. if (booleanString === "!true") {
  64455. booleanString = "false";
  64456. }
  64457. else if (booleanString === "!false") {
  64458. booleanString = "true";
  64459. }
  64460. return booleanString;
  64461. };
  64462. return AndOrNotEvaluator;
  64463. }());
  64464. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64465. })(BABYLON || (BABYLON = {}));
  64466. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64467. "use strict";
  64468. var BABYLON;
  64469. (function (BABYLON) {
  64470. var Database = /** @class */ (function () {
  64471. function Database(urlToScene, callbackManifestChecked) {
  64472. // Handling various flavors of prefixed version of IndexedDB
  64473. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64474. this.callbackManifestChecked = callbackManifestChecked;
  64475. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64476. this.db = null;
  64477. this._enableSceneOffline = false;
  64478. this._enableTexturesOffline = false;
  64479. this.manifestVersionFound = 0;
  64480. this.mustUpdateRessources = false;
  64481. this.hasReachedQuota = false;
  64482. if (!Database.IDBStorageEnabled) {
  64483. this.callbackManifestChecked(true);
  64484. }
  64485. else {
  64486. this.checkManifestFile();
  64487. }
  64488. }
  64489. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64490. get: function () {
  64491. return this._enableSceneOffline;
  64492. },
  64493. enumerable: true,
  64494. configurable: true
  64495. });
  64496. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64497. get: function () {
  64498. return this._enableTexturesOffline;
  64499. },
  64500. enumerable: true,
  64501. configurable: true
  64502. });
  64503. Database.prototype.checkManifestFile = function () {
  64504. var _this = this;
  64505. var noManifestFile = function () {
  64506. _this._enableSceneOffline = false;
  64507. _this._enableTexturesOffline = false;
  64508. _this.callbackManifestChecked(false);
  64509. };
  64510. var timeStampUsed = false;
  64511. var manifestURL = this.currentSceneUrl + ".manifest";
  64512. var xhr = new XMLHttpRequest();
  64513. if (navigator.onLine) {
  64514. // Adding a timestamp to by-pass browsers' cache
  64515. timeStampUsed = true;
  64516. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64517. }
  64518. xhr.open("GET", manifestURL, true);
  64519. xhr.addEventListener("load", function () {
  64520. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64521. try {
  64522. var manifestFile = JSON.parse(xhr.response);
  64523. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64524. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64525. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64526. _this.manifestVersionFound = manifestFile.version;
  64527. }
  64528. if (_this.callbackManifestChecked) {
  64529. _this.callbackManifestChecked(true);
  64530. }
  64531. }
  64532. catch (ex) {
  64533. noManifestFile();
  64534. }
  64535. }
  64536. else {
  64537. noManifestFile();
  64538. }
  64539. }, false);
  64540. xhr.addEventListener("error", function (event) {
  64541. if (timeStampUsed) {
  64542. timeStampUsed = false;
  64543. // Let's retry without the timeStamp
  64544. // It could fail when coupled with HTML5 Offline API
  64545. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64546. xhr.open("GET", retryManifestURL, true);
  64547. xhr.send();
  64548. }
  64549. else {
  64550. noManifestFile();
  64551. }
  64552. }, false);
  64553. try {
  64554. xhr.send();
  64555. }
  64556. catch (ex) {
  64557. BABYLON.Tools.Error("Error on XHR send request.");
  64558. this.callbackManifestChecked(false);
  64559. }
  64560. };
  64561. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64562. var _this = this;
  64563. var handleError = function () {
  64564. _this.isSupported = false;
  64565. if (errorCallback)
  64566. errorCallback();
  64567. };
  64568. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64569. // Your browser doesn't support IndexedDB
  64570. this.isSupported = false;
  64571. if (errorCallback)
  64572. errorCallback();
  64573. }
  64574. else {
  64575. // If the DB hasn't been opened or created yet
  64576. if (!this.db) {
  64577. this.hasReachedQuota = false;
  64578. this.isSupported = true;
  64579. var request = this.idbFactory.open("babylonjs", 1);
  64580. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64581. request.onerror = function (event) {
  64582. handleError();
  64583. };
  64584. // executes when a version change transaction cannot complete due to other active transactions
  64585. request.onblocked = function (event) {
  64586. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64587. handleError();
  64588. };
  64589. // DB has been opened successfully
  64590. request.onsuccess = function (event) {
  64591. _this.db = request.result;
  64592. successCallback();
  64593. };
  64594. // Initialization of the DB. Creating Scenes & Textures stores
  64595. request.onupgradeneeded = function (event) {
  64596. _this.db = (event.target).result;
  64597. if (_this.db) {
  64598. try {
  64599. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64600. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64601. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64602. }
  64603. catch (ex) {
  64604. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64605. handleError();
  64606. }
  64607. }
  64608. };
  64609. }
  64610. else {
  64611. if (successCallback)
  64612. successCallback();
  64613. }
  64614. }
  64615. };
  64616. Database.prototype.loadImageFromDB = function (url, image) {
  64617. var _this = this;
  64618. var completeURL = Database.ReturnFullUrlLocation(url);
  64619. var saveAndLoadImage = function () {
  64620. if (!_this.hasReachedQuota && _this.db !== null) {
  64621. // the texture is not yet in the DB, let's try to save it
  64622. _this._saveImageIntoDBAsync(completeURL, image);
  64623. }
  64624. else {
  64625. image.src = url;
  64626. }
  64627. };
  64628. if (!this.mustUpdateRessources) {
  64629. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64630. }
  64631. else {
  64632. saveAndLoadImage();
  64633. }
  64634. };
  64635. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64636. if (this.isSupported && this.db !== null) {
  64637. var texture;
  64638. var transaction = this.db.transaction(["textures"]);
  64639. transaction.onabort = function (event) {
  64640. image.src = url;
  64641. };
  64642. transaction.oncomplete = function (event) {
  64643. var blobTextureURL;
  64644. if (texture) {
  64645. var URL = window.URL || window.webkitURL;
  64646. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64647. image.onerror = function () {
  64648. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64649. image.src = url;
  64650. };
  64651. image.src = blobTextureURL;
  64652. }
  64653. else {
  64654. notInDBCallback();
  64655. }
  64656. };
  64657. var getRequest = transaction.objectStore("textures").get(url);
  64658. getRequest.onsuccess = function (event) {
  64659. texture = (event.target).result;
  64660. };
  64661. getRequest.onerror = function (event) {
  64662. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64663. image.src = url;
  64664. };
  64665. }
  64666. else {
  64667. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64668. image.src = url;
  64669. }
  64670. };
  64671. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64672. var _this = this;
  64673. if (this.isSupported) {
  64674. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64675. var generateBlobUrl = function () {
  64676. var blobTextureURL;
  64677. if (blob) {
  64678. var URL = window.URL || window.webkitURL;
  64679. try {
  64680. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64681. }
  64682. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64683. catch (ex) {
  64684. blobTextureURL = URL.createObjectURL(blob);
  64685. }
  64686. }
  64687. if (blobTextureURL) {
  64688. image.src = blobTextureURL;
  64689. }
  64690. };
  64691. if (Database.IsUASupportingBlobStorage) {
  64692. var xhr = new XMLHttpRequest(), blob;
  64693. xhr.open("GET", url, true);
  64694. xhr.responseType = "blob";
  64695. xhr.addEventListener("load", function () {
  64696. if (xhr.status === 200 && _this.db) {
  64697. // Blob as response (XHR2)
  64698. blob = xhr.response;
  64699. var transaction = _this.db.transaction(["textures"], "readwrite");
  64700. // the transaction could abort because of a QuotaExceededError error
  64701. transaction.onabort = function (event) {
  64702. try {
  64703. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64704. var srcElement = (event.srcElement || event.target);
  64705. var error = srcElement.error;
  64706. if (error && error.name === "QuotaExceededError") {
  64707. _this.hasReachedQuota = true;
  64708. }
  64709. }
  64710. catch (ex) { }
  64711. generateBlobUrl();
  64712. };
  64713. transaction.oncomplete = function (event) {
  64714. generateBlobUrl();
  64715. };
  64716. var newTexture = { textureUrl: url, data: blob };
  64717. try {
  64718. // Put the blob into the dabase
  64719. var addRequest = transaction.objectStore("textures").put(newTexture);
  64720. addRequest.onsuccess = function (event) {
  64721. };
  64722. addRequest.onerror = function (event) {
  64723. generateBlobUrl();
  64724. };
  64725. }
  64726. catch (ex) {
  64727. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64728. if (ex.code === 25) {
  64729. Database.IsUASupportingBlobStorage = false;
  64730. }
  64731. image.src = url;
  64732. }
  64733. }
  64734. else {
  64735. image.src = url;
  64736. }
  64737. }, false);
  64738. xhr.addEventListener("error", function (event) {
  64739. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64740. image.src = url;
  64741. }, false);
  64742. xhr.send();
  64743. }
  64744. else {
  64745. image.src = url;
  64746. }
  64747. }
  64748. else {
  64749. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64750. image.src = url;
  64751. }
  64752. };
  64753. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64754. var _this = this;
  64755. var updateVersion = function () {
  64756. // the version is not yet in the DB or we need to update it
  64757. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64758. };
  64759. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64760. };
  64761. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64762. var _this = this;
  64763. if (this.isSupported && this.db) {
  64764. var version;
  64765. try {
  64766. var transaction = this.db.transaction(["versions"]);
  64767. transaction.oncomplete = function (event) {
  64768. if (version) {
  64769. // If the version in the JSON file is > than the version in DB
  64770. if (_this.manifestVersionFound > version.data) {
  64771. _this.mustUpdateRessources = true;
  64772. updateInDBCallback();
  64773. }
  64774. else {
  64775. callback(version.data);
  64776. }
  64777. }
  64778. else {
  64779. _this.mustUpdateRessources = true;
  64780. updateInDBCallback();
  64781. }
  64782. };
  64783. transaction.onabort = function (event) {
  64784. callback(-1);
  64785. };
  64786. var getRequest = transaction.objectStore("versions").get(url);
  64787. getRequest.onsuccess = function (event) {
  64788. version = (event.target).result;
  64789. };
  64790. getRequest.onerror = function (event) {
  64791. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64792. callback(-1);
  64793. };
  64794. }
  64795. catch (ex) {
  64796. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64797. callback(-1);
  64798. }
  64799. }
  64800. else {
  64801. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64802. callback(-1);
  64803. }
  64804. };
  64805. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64806. var _this = this;
  64807. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64808. try {
  64809. // Open a transaction to the database
  64810. var transaction = this.db.transaction(["versions"], "readwrite");
  64811. // the transaction could abort because of a QuotaExceededError error
  64812. transaction.onabort = function (event) {
  64813. try {
  64814. var error = event.srcElement['error'];
  64815. if (error && error.name === "QuotaExceededError") {
  64816. _this.hasReachedQuota = true;
  64817. }
  64818. }
  64819. catch (ex) { }
  64820. callback(-1);
  64821. };
  64822. transaction.oncomplete = function (event) {
  64823. callback(_this.manifestVersionFound);
  64824. };
  64825. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64826. // Put the scene into the database
  64827. var addRequest = transaction.objectStore("versions").put(newVersion);
  64828. addRequest.onsuccess = function (event) {
  64829. };
  64830. addRequest.onerror = function (event) {
  64831. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64832. };
  64833. }
  64834. catch (ex) {
  64835. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64836. callback(-1);
  64837. }
  64838. }
  64839. else {
  64840. callback(-1);
  64841. }
  64842. };
  64843. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64844. var _this = this;
  64845. var completeUrl = Database.ReturnFullUrlLocation(url);
  64846. var saveAndLoadFile = function () {
  64847. // the scene is not yet in the DB, let's try to save it
  64848. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64849. };
  64850. this._checkVersionFromDB(completeUrl, function (version) {
  64851. if (version !== -1) {
  64852. if (!_this.mustUpdateRessources) {
  64853. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64854. }
  64855. else {
  64856. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64857. }
  64858. }
  64859. else {
  64860. if (errorCallback) {
  64861. errorCallback();
  64862. }
  64863. }
  64864. });
  64865. };
  64866. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64867. if (this.isSupported && this.db) {
  64868. var targetStore;
  64869. if (url.indexOf(".babylon") !== -1) {
  64870. targetStore = "scenes";
  64871. }
  64872. else {
  64873. targetStore = "textures";
  64874. }
  64875. var file;
  64876. var transaction = this.db.transaction([targetStore]);
  64877. transaction.oncomplete = function (event) {
  64878. if (file) {
  64879. callback(file.data);
  64880. }
  64881. else {
  64882. notInDBCallback();
  64883. }
  64884. };
  64885. transaction.onabort = function (event) {
  64886. notInDBCallback();
  64887. };
  64888. var getRequest = transaction.objectStore(targetStore).get(url);
  64889. getRequest.onsuccess = function (event) {
  64890. file = (event.target).result;
  64891. };
  64892. getRequest.onerror = function (event) {
  64893. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64894. notInDBCallback();
  64895. };
  64896. }
  64897. else {
  64898. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64899. callback();
  64900. }
  64901. };
  64902. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64903. var _this = this;
  64904. if (this.isSupported) {
  64905. var targetStore;
  64906. if (url.indexOf(".babylon") !== -1) {
  64907. targetStore = "scenes";
  64908. }
  64909. else {
  64910. targetStore = "textures";
  64911. }
  64912. // Create XHR
  64913. var xhr = new XMLHttpRequest();
  64914. var fileData;
  64915. xhr.open("GET", url, true);
  64916. if (useArrayBuffer) {
  64917. xhr.responseType = "arraybuffer";
  64918. }
  64919. if (progressCallback) {
  64920. xhr.onprogress = progressCallback;
  64921. }
  64922. xhr.addEventListener("load", function () {
  64923. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64924. // Blob as response (XHR2)
  64925. //fileData = xhr.responseText;
  64926. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64927. if (!_this.hasReachedQuota && _this.db) {
  64928. // Open a transaction to the database
  64929. var transaction = _this.db.transaction([targetStore], "readwrite");
  64930. // the transaction could abort because of a QuotaExceededError error
  64931. transaction.onabort = function (event) {
  64932. try {
  64933. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64934. var error = event.srcElement['error'];
  64935. if (error && error.name === "QuotaExceededError") {
  64936. _this.hasReachedQuota = true;
  64937. }
  64938. }
  64939. catch (ex) { }
  64940. callback(fileData);
  64941. };
  64942. transaction.oncomplete = function (event) {
  64943. callback(fileData);
  64944. };
  64945. var newFile;
  64946. if (targetStore === "scenes") {
  64947. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64948. }
  64949. else {
  64950. newFile = { textureUrl: url, data: fileData };
  64951. }
  64952. try {
  64953. // Put the scene into the database
  64954. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64955. addRequest.onsuccess = function (event) {
  64956. };
  64957. addRequest.onerror = function (event) {
  64958. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64959. };
  64960. }
  64961. catch (ex) {
  64962. callback(fileData);
  64963. }
  64964. }
  64965. else {
  64966. callback(fileData);
  64967. }
  64968. }
  64969. else {
  64970. callback();
  64971. }
  64972. }, false);
  64973. xhr.addEventListener("error", function (event) {
  64974. BABYLON.Tools.Error("error on XHR request.");
  64975. callback();
  64976. }, false);
  64977. xhr.send();
  64978. }
  64979. else {
  64980. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64981. callback();
  64982. }
  64983. };
  64984. Database.IsUASupportingBlobStorage = true;
  64985. Database.IDBStorageEnabled = true;
  64986. Database.parseURL = function (url) {
  64987. var a = document.createElement('a');
  64988. a.href = url;
  64989. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64990. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64991. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64992. return absLocation;
  64993. };
  64994. Database.ReturnFullUrlLocation = function (url) {
  64995. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64996. return (Database.parseURL(window.location.href) + url);
  64997. }
  64998. else {
  64999. return url;
  65000. }
  65001. };
  65002. return Database;
  65003. }());
  65004. BABYLON.Database = Database;
  65005. })(BABYLON || (BABYLON = {}));
  65006. //# sourceMappingURL=babylon.database.js.map
  65007. "use strict";
  65008. var BABYLON;
  65009. (function (BABYLON) {
  65010. var FresnelParameters = /** @class */ (function () {
  65011. function FresnelParameters() {
  65012. this._isEnabled = true;
  65013. this.leftColor = BABYLON.Color3.White();
  65014. this.rightColor = BABYLON.Color3.Black();
  65015. this.bias = 0;
  65016. this.power = 1;
  65017. }
  65018. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  65019. get: function () {
  65020. return this._isEnabled;
  65021. },
  65022. set: function (value) {
  65023. if (this._isEnabled === value) {
  65024. return;
  65025. }
  65026. this._isEnabled = value;
  65027. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  65028. },
  65029. enumerable: true,
  65030. configurable: true
  65031. });
  65032. FresnelParameters.prototype.clone = function () {
  65033. var newFresnelParameters = new FresnelParameters();
  65034. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  65035. return newFresnelParameters;
  65036. };
  65037. FresnelParameters.prototype.serialize = function () {
  65038. var serializationObject = {};
  65039. serializationObject.isEnabled = this.isEnabled;
  65040. serializationObject.leftColor = this.leftColor.asArray();
  65041. serializationObject.rightColor = this.rightColor.asArray();
  65042. serializationObject.bias = this.bias;
  65043. serializationObject.power = this.power;
  65044. return serializationObject;
  65045. };
  65046. FresnelParameters.Parse = function (parsedFresnelParameters) {
  65047. var fresnelParameters = new FresnelParameters();
  65048. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  65049. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  65050. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  65051. fresnelParameters.bias = parsedFresnelParameters.bias;
  65052. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  65053. return fresnelParameters;
  65054. };
  65055. return FresnelParameters;
  65056. }());
  65057. BABYLON.FresnelParameters = FresnelParameters;
  65058. })(BABYLON || (BABYLON = {}));
  65059. //# sourceMappingURL=babylon.fresnelParameters.js.map
  65060. "use strict";
  65061. var BABYLON;
  65062. (function (BABYLON) {
  65063. var MultiMaterial = /** @class */ (function (_super) {
  65064. __extends(MultiMaterial, _super);
  65065. function MultiMaterial(name, scene) {
  65066. var _this = _super.call(this, name, scene, true) || this;
  65067. scene.multiMaterials.push(_this);
  65068. _this.subMaterials = new Array();
  65069. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  65070. return _this;
  65071. }
  65072. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  65073. get: function () {
  65074. return this._subMaterials;
  65075. },
  65076. set: function (value) {
  65077. this._subMaterials = value;
  65078. this._hookArray(value);
  65079. },
  65080. enumerable: true,
  65081. configurable: true
  65082. });
  65083. MultiMaterial.prototype._hookArray = function (array) {
  65084. var _this = this;
  65085. var oldPush = array.push;
  65086. array.push = function () {
  65087. var items = [];
  65088. for (var _i = 0; _i < arguments.length; _i++) {
  65089. items[_i] = arguments[_i];
  65090. }
  65091. var result = oldPush.apply(array, items);
  65092. _this._markAllSubMeshesAsTexturesDirty();
  65093. return result;
  65094. };
  65095. var oldSplice = array.splice;
  65096. array.splice = function (index, deleteCount) {
  65097. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65098. _this._markAllSubMeshesAsTexturesDirty();
  65099. return deleted;
  65100. };
  65101. };
  65102. // Properties
  65103. MultiMaterial.prototype.getSubMaterial = function (index) {
  65104. if (index < 0 || index >= this.subMaterials.length) {
  65105. return this.getScene().defaultMaterial;
  65106. }
  65107. return this.subMaterials[index];
  65108. };
  65109. MultiMaterial.prototype.getActiveTextures = function () {
  65110. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  65111. if (subMaterial) {
  65112. return subMaterial.getActiveTextures();
  65113. }
  65114. else {
  65115. return [];
  65116. }
  65117. }));
  65118. var _a;
  65119. };
  65120. // Methods
  65121. MultiMaterial.prototype.getClassName = function () {
  65122. return "MultiMaterial";
  65123. };
  65124. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  65125. for (var index = 0; index < this.subMaterials.length; index++) {
  65126. var subMaterial = this.subMaterials[index];
  65127. if (subMaterial) {
  65128. if (subMaterial.storeEffectOnSubMeshes) {
  65129. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  65130. return false;
  65131. }
  65132. continue;
  65133. }
  65134. if (!subMaterial.isReady(mesh)) {
  65135. return false;
  65136. }
  65137. }
  65138. }
  65139. return true;
  65140. };
  65141. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  65142. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  65143. for (var index = 0; index < this.subMaterials.length; index++) {
  65144. var subMaterial = null;
  65145. var current = this.subMaterials[index];
  65146. if (cloneChildren && current) {
  65147. subMaterial = current.clone(name + "-" + current.name);
  65148. }
  65149. else {
  65150. subMaterial = this.subMaterials[index];
  65151. }
  65152. newMultiMaterial.subMaterials.push(subMaterial);
  65153. }
  65154. return newMultiMaterial;
  65155. };
  65156. MultiMaterial.prototype.serialize = function () {
  65157. var serializationObject = {};
  65158. serializationObject.name = this.name;
  65159. serializationObject.id = this.id;
  65160. if (BABYLON.Tags) {
  65161. serializationObject.tags = BABYLON.Tags.GetTags(this);
  65162. }
  65163. serializationObject.materials = [];
  65164. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  65165. var subMat = this.subMaterials[matIndex];
  65166. if (subMat) {
  65167. serializationObject.materials.push(subMat.id);
  65168. }
  65169. else {
  65170. serializationObject.materials.push(null);
  65171. }
  65172. }
  65173. return serializationObject;
  65174. };
  65175. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  65176. var scene = this.getScene();
  65177. if (!scene) {
  65178. return;
  65179. }
  65180. var index = scene.multiMaterials.indexOf(this);
  65181. if (index >= 0) {
  65182. scene.multiMaterials.splice(index, 1);
  65183. }
  65184. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  65185. };
  65186. return MultiMaterial;
  65187. }(BABYLON.Material));
  65188. BABYLON.MultiMaterial = MultiMaterial;
  65189. })(BABYLON || (BABYLON = {}));
  65190. //# sourceMappingURL=babylon.multiMaterial.js.map
  65191. "use strict";
  65192. var BABYLON;
  65193. (function (BABYLON) {
  65194. var FreeCameraTouchInput = /** @class */ (function () {
  65195. function FreeCameraTouchInput() {
  65196. this._offsetX = null;
  65197. this._offsetY = null;
  65198. this._pointerPressed = new Array();
  65199. this.touchAngularSensibility = 200000.0;
  65200. this.touchMoveSensibility = 250.0;
  65201. }
  65202. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  65203. var _this = this;
  65204. var previousPosition = null;
  65205. if (this._pointerInput === undefined) {
  65206. this._onLostFocus = function (evt) {
  65207. _this._offsetX = null;
  65208. _this._offsetY = null;
  65209. };
  65210. this._pointerInput = function (p, s) {
  65211. var evt = p.event;
  65212. if (evt.pointerType === "mouse") {
  65213. return;
  65214. }
  65215. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  65216. if (!noPreventDefault) {
  65217. evt.preventDefault();
  65218. }
  65219. _this._pointerPressed.push(evt.pointerId);
  65220. if (_this._pointerPressed.length !== 1) {
  65221. return;
  65222. }
  65223. previousPosition = {
  65224. x: evt.clientX,
  65225. y: evt.clientY
  65226. };
  65227. }
  65228. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  65229. if (!noPreventDefault) {
  65230. evt.preventDefault();
  65231. }
  65232. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65233. if (index === -1) {
  65234. return;
  65235. }
  65236. _this._pointerPressed.splice(index, 1);
  65237. if (index != 0) {
  65238. return;
  65239. }
  65240. previousPosition = null;
  65241. _this._offsetX = null;
  65242. _this._offsetY = null;
  65243. }
  65244. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  65245. if (!noPreventDefault) {
  65246. evt.preventDefault();
  65247. }
  65248. if (!previousPosition) {
  65249. return;
  65250. }
  65251. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65252. if (index != 0) {
  65253. return;
  65254. }
  65255. _this._offsetX = evt.clientX - previousPosition.x;
  65256. _this._offsetY = -(evt.clientY - previousPosition.y);
  65257. }
  65258. };
  65259. }
  65260. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  65261. if (this._onLostFocus) {
  65262. element.addEventListener("blur", this._onLostFocus);
  65263. }
  65264. };
  65265. FreeCameraTouchInput.prototype.detachControl = function (element) {
  65266. if (this._pointerInput && element) {
  65267. if (this._observer) {
  65268. this.camera.getScene().onPointerObservable.remove(this._observer);
  65269. this._observer = null;
  65270. }
  65271. if (this._onLostFocus) {
  65272. element.removeEventListener("blur", this._onLostFocus);
  65273. this._onLostFocus = null;
  65274. }
  65275. this._pointerPressed = [];
  65276. this._offsetX = null;
  65277. this._offsetY = null;
  65278. }
  65279. };
  65280. FreeCameraTouchInput.prototype.checkInputs = function () {
  65281. if (this._offsetX && this._offsetY) {
  65282. var camera = this.camera;
  65283. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  65284. if (this._pointerPressed.length > 1) {
  65285. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  65286. }
  65287. else {
  65288. var speed = camera._computeLocalCameraSpeed();
  65289. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  65290. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  65291. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  65292. }
  65293. }
  65294. };
  65295. FreeCameraTouchInput.prototype.getClassName = function () {
  65296. return "FreeCameraTouchInput";
  65297. };
  65298. FreeCameraTouchInput.prototype.getSimpleName = function () {
  65299. return "touch";
  65300. };
  65301. __decorate([
  65302. BABYLON.serialize()
  65303. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  65304. __decorate([
  65305. BABYLON.serialize()
  65306. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  65307. return FreeCameraTouchInput;
  65308. }());
  65309. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65310. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65311. })(BABYLON || (BABYLON = {}));
  65312. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65313. "use strict";
  65314. var BABYLON;
  65315. (function (BABYLON) {
  65316. // We're mainly based on the logic defined into the FreeCamera code
  65317. var TouchCamera = /** @class */ (function (_super) {
  65318. __extends(TouchCamera, _super);
  65319. //-- end properties for backward compatibility for inputs
  65320. function TouchCamera(name, position, scene) {
  65321. var _this = _super.call(this, name, position, scene) || this;
  65322. _this.inputs.addTouch();
  65323. _this._setupInputs();
  65324. return _this;
  65325. }
  65326. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65327. //-- Begin properties for backward compatibility for inputs
  65328. get: function () {
  65329. var touch = this.inputs.attached["touch"];
  65330. if (touch)
  65331. return touch.touchAngularSensibility;
  65332. return 0;
  65333. },
  65334. set: function (value) {
  65335. var touch = this.inputs.attached["touch"];
  65336. if (touch)
  65337. touch.touchAngularSensibility = value;
  65338. },
  65339. enumerable: true,
  65340. configurable: true
  65341. });
  65342. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65343. get: function () {
  65344. var touch = this.inputs.attached["touch"];
  65345. if (touch)
  65346. return touch.touchMoveSensibility;
  65347. return 0;
  65348. },
  65349. set: function (value) {
  65350. var touch = this.inputs.attached["touch"];
  65351. if (touch)
  65352. touch.touchMoveSensibility = value;
  65353. },
  65354. enumerable: true,
  65355. configurable: true
  65356. });
  65357. TouchCamera.prototype.getClassName = function () {
  65358. return "TouchCamera";
  65359. };
  65360. TouchCamera.prototype._setupInputs = function () {
  65361. var mouse = this.inputs.attached["mouse"];
  65362. if (mouse) {
  65363. mouse.touchEnabled = false;
  65364. }
  65365. };
  65366. return TouchCamera;
  65367. }(BABYLON.FreeCamera));
  65368. BABYLON.TouchCamera = TouchCamera;
  65369. })(BABYLON || (BABYLON = {}));
  65370. //# sourceMappingURL=babylon.touchCamera.js.map
  65371. "use strict";
  65372. var BABYLON;
  65373. (function (BABYLON) {
  65374. var ProceduralTexture = /** @class */ (function (_super) {
  65375. __extends(ProceduralTexture, _super);
  65376. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65377. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65378. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65379. if (isCube === void 0) { isCube = false; }
  65380. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65381. _this.isCube = isCube;
  65382. _this.isEnabled = true;
  65383. _this._currentRefreshId = -1;
  65384. _this._refreshRate = 1;
  65385. _this._vertexBuffers = {};
  65386. _this._uniforms = new Array();
  65387. _this._samplers = new Array();
  65388. _this._textures = {};
  65389. _this._floats = {};
  65390. _this._floatsArrays = {};
  65391. _this._colors3 = {};
  65392. _this._colors4 = {};
  65393. _this._vectors2 = {};
  65394. _this._vectors3 = {};
  65395. _this._matrices = {};
  65396. _this._fallbackTextureUsed = false;
  65397. scene._proceduralTextures.push(_this);
  65398. _this._engine = scene.getEngine();
  65399. _this.name = name;
  65400. _this.isRenderTarget = true;
  65401. _this._size = size;
  65402. _this._generateMipMaps = generateMipMaps;
  65403. _this.setFragment(fragment);
  65404. _this._fallbackTexture = fallbackTexture;
  65405. if (isCube) {
  65406. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65407. _this.setFloat("face", 0);
  65408. }
  65409. else {
  65410. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65411. }
  65412. // VBO
  65413. var vertices = [];
  65414. vertices.push(1, 1);
  65415. vertices.push(-1, 1);
  65416. vertices.push(-1, -1);
  65417. vertices.push(1, -1);
  65418. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65419. _this._createIndexBuffer();
  65420. return _this;
  65421. }
  65422. ProceduralTexture.prototype._createIndexBuffer = function () {
  65423. var engine = this._engine;
  65424. // Indices
  65425. var indices = [];
  65426. indices.push(0);
  65427. indices.push(1);
  65428. indices.push(2);
  65429. indices.push(0);
  65430. indices.push(2);
  65431. indices.push(3);
  65432. this._indexBuffer = engine.createIndexBuffer(indices);
  65433. };
  65434. ProceduralTexture.prototype._rebuild = function () {
  65435. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65436. if (vb) {
  65437. vb._rebuild();
  65438. }
  65439. this._createIndexBuffer();
  65440. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65441. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65442. }
  65443. };
  65444. ProceduralTexture.prototype.reset = function () {
  65445. if (this._effect === undefined) {
  65446. return;
  65447. }
  65448. var engine = this._engine;
  65449. engine._releaseEffect(this._effect);
  65450. };
  65451. ProceduralTexture.prototype.isReady = function () {
  65452. var _this = this;
  65453. var engine = this._engine;
  65454. var shaders;
  65455. if (!this._fragment) {
  65456. return false;
  65457. }
  65458. if (this._fallbackTextureUsed) {
  65459. return true;
  65460. }
  65461. if (this._fragment.fragmentElement !== undefined) {
  65462. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65463. }
  65464. else {
  65465. shaders = { vertex: "procedural", fragment: this._fragment };
  65466. }
  65467. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65468. _this.releaseInternalTexture();
  65469. if (_this._fallbackTexture) {
  65470. _this._texture = _this._fallbackTexture._texture;
  65471. if (_this._texture) {
  65472. _this._texture.incrementReferences();
  65473. }
  65474. }
  65475. _this._fallbackTextureUsed = true;
  65476. });
  65477. return this._effect.isReady();
  65478. };
  65479. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65480. this._currentRefreshId = -1;
  65481. };
  65482. ProceduralTexture.prototype.setFragment = function (fragment) {
  65483. this._fragment = fragment;
  65484. };
  65485. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65486. get: function () {
  65487. return this._refreshRate;
  65488. },
  65489. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65490. set: function (value) {
  65491. this._refreshRate = value;
  65492. this.resetRefreshCounter();
  65493. },
  65494. enumerable: true,
  65495. configurable: true
  65496. });
  65497. ProceduralTexture.prototype._shouldRender = function () {
  65498. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65499. return false;
  65500. }
  65501. if (this._fallbackTextureUsed) {
  65502. return false;
  65503. }
  65504. if (this._currentRefreshId === -1) {
  65505. this._currentRefreshId = 1;
  65506. return true;
  65507. }
  65508. if (this.refreshRate === this._currentRefreshId) {
  65509. this._currentRefreshId = 1;
  65510. return true;
  65511. }
  65512. this._currentRefreshId++;
  65513. return false;
  65514. };
  65515. ProceduralTexture.prototype.getRenderSize = function () {
  65516. return this._size;
  65517. };
  65518. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65519. if (this._fallbackTextureUsed) {
  65520. return;
  65521. }
  65522. this.releaseInternalTexture();
  65523. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65524. };
  65525. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65526. if (this._uniforms.indexOf(uniformName) === -1) {
  65527. this._uniforms.push(uniformName);
  65528. }
  65529. };
  65530. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65531. if (this._samplers.indexOf(name) === -1) {
  65532. this._samplers.push(name);
  65533. }
  65534. this._textures[name] = texture;
  65535. return this;
  65536. };
  65537. ProceduralTexture.prototype.setFloat = function (name, value) {
  65538. this._checkUniform(name);
  65539. this._floats[name] = value;
  65540. return this;
  65541. };
  65542. ProceduralTexture.prototype.setFloats = function (name, value) {
  65543. this._checkUniform(name);
  65544. this._floatsArrays[name] = value;
  65545. return this;
  65546. };
  65547. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65548. this._checkUniform(name);
  65549. this._colors3[name] = value;
  65550. return this;
  65551. };
  65552. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65553. this._checkUniform(name);
  65554. this._colors4[name] = value;
  65555. return this;
  65556. };
  65557. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65558. this._checkUniform(name);
  65559. this._vectors2[name] = value;
  65560. return this;
  65561. };
  65562. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65563. this._checkUniform(name);
  65564. this._vectors3[name] = value;
  65565. return this;
  65566. };
  65567. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65568. this._checkUniform(name);
  65569. this._matrices[name] = value;
  65570. return this;
  65571. };
  65572. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65573. var scene = this.getScene();
  65574. if (!scene) {
  65575. return;
  65576. }
  65577. var engine = this._engine;
  65578. // Render
  65579. engine.enableEffect(this._effect);
  65580. engine.setState(false);
  65581. // Texture
  65582. for (var name in this._textures) {
  65583. this._effect.setTexture(name, this._textures[name]);
  65584. }
  65585. // Float
  65586. for (name in this._floats) {
  65587. this._effect.setFloat(name, this._floats[name]);
  65588. }
  65589. // Floats
  65590. for (name in this._floatsArrays) {
  65591. this._effect.setArray(name, this._floatsArrays[name]);
  65592. }
  65593. // Color3
  65594. for (name in this._colors3) {
  65595. this._effect.setColor3(name, this._colors3[name]);
  65596. }
  65597. // Color4
  65598. for (name in this._colors4) {
  65599. var color = this._colors4[name];
  65600. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65601. }
  65602. // Vector2
  65603. for (name in this._vectors2) {
  65604. this._effect.setVector2(name, this._vectors2[name]);
  65605. }
  65606. // Vector3
  65607. for (name in this._vectors3) {
  65608. this._effect.setVector3(name, this._vectors3[name]);
  65609. }
  65610. // Matrix
  65611. for (name in this._matrices) {
  65612. this._effect.setMatrix(name, this._matrices[name]);
  65613. }
  65614. if (!this._texture) {
  65615. return;
  65616. }
  65617. if (this.isCube) {
  65618. for (var face = 0; face < 6; face++) {
  65619. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65620. // VBOs
  65621. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65622. this._effect.setFloat("face", face);
  65623. // Clear
  65624. engine.clear(scene.clearColor, true, true, true);
  65625. // Draw order
  65626. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65627. // Mipmaps
  65628. if (face === 5) {
  65629. engine.generateMipMapsForCubemap(this._texture);
  65630. }
  65631. }
  65632. }
  65633. else {
  65634. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65635. // VBOs
  65636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65637. // Clear
  65638. engine.clear(scene.clearColor, true, true, true);
  65639. // Draw order
  65640. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65641. }
  65642. // Unbind
  65643. engine.unBindFramebuffer(this._texture, this.isCube);
  65644. if (this.onGenerated) {
  65645. this.onGenerated();
  65646. }
  65647. };
  65648. ProceduralTexture.prototype.clone = function () {
  65649. var textureSize = this.getSize();
  65650. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65651. // Base texture
  65652. newTexture.hasAlpha = this.hasAlpha;
  65653. newTexture.level = this.level;
  65654. // RenderTarget Texture
  65655. newTexture.coordinatesMode = this.coordinatesMode;
  65656. return newTexture;
  65657. };
  65658. ProceduralTexture.prototype.dispose = function () {
  65659. var scene = this.getScene();
  65660. if (!scene) {
  65661. return;
  65662. }
  65663. var index = scene._proceduralTextures.indexOf(this);
  65664. if (index >= 0) {
  65665. scene._proceduralTextures.splice(index, 1);
  65666. }
  65667. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65668. if (vertexBuffer) {
  65669. vertexBuffer.dispose();
  65670. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65671. }
  65672. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65673. this._indexBuffer = null;
  65674. }
  65675. _super.prototype.dispose.call(this);
  65676. };
  65677. return ProceduralTexture;
  65678. }(BABYLON.Texture));
  65679. BABYLON.ProceduralTexture = ProceduralTexture;
  65680. })(BABYLON || (BABYLON = {}));
  65681. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65682. "use strict";
  65683. var BABYLON;
  65684. (function (BABYLON) {
  65685. var CustomProceduralTexture = /** @class */ (function (_super) {
  65686. __extends(CustomProceduralTexture, _super);
  65687. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65688. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65689. _this._animate = true;
  65690. _this._time = 0;
  65691. _this._texturePath = texturePath;
  65692. //Try to load json
  65693. _this.loadJson(texturePath);
  65694. _this.refreshRate = 1;
  65695. return _this;
  65696. }
  65697. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65698. var _this = this;
  65699. var noConfigFile = function () {
  65700. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65701. try {
  65702. _this.setFragment(_this._texturePath);
  65703. }
  65704. catch (ex) {
  65705. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65706. }
  65707. };
  65708. var configFileUrl = jsonUrl + "/config.json";
  65709. var xhr = new XMLHttpRequest();
  65710. xhr.open("GET", configFileUrl, true);
  65711. xhr.addEventListener("load", function () {
  65712. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65713. try {
  65714. _this._config = JSON.parse(xhr.response);
  65715. _this.updateShaderUniforms();
  65716. _this.updateTextures();
  65717. _this.setFragment(_this._texturePath + "/custom");
  65718. _this._animate = _this._config.animate;
  65719. _this.refreshRate = _this._config.refreshrate;
  65720. }
  65721. catch (ex) {
  65722. noConfigFile();
  65723. }
  65724. }
  65725. else {
  65726. noConfigFile();
  65727. }
  65728. }, false);
  65729. xhr.addEventListener("error", function () {
  65730. noConfigFile();
  65731. }, false);
  65732. try {
  65733. xhr.send();
  65734. }
  65735. catch (ex) {
  65736. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65737. }
  65738. };
  65739. CustomProceduralTexture.prototype.isReady = function () {
  65740. if (!_super.prototype.isReady.call(this)) {
  65741. return false;
  65742. }
  65743. for (var name in this._textures) {
  65744. var texture = this._textures[name];
  65745. if (!texture.isReady()) {
  65746. return false;
  65747. }
  65748. }
  65749. return true;
  65750. };
  65751. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65752. var scene = this.getScene();
  65753. if (this._animate && scene) {
  65754. this._time += scene.getAnimationRatio() * 0.03;
  65755. this.updateShaderUniforms();
  65756. }
  65757. _super.prototype.render.call(this, useCameraPostProcess);
  65758. };
  65759. CustomProceduralTexture.prototype.updateTextures = function () {
  65760. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65761. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65762. }
  65763. };
  65764. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65765. if (this._config) {
  65766. for (var j = 0; j < this._config.uniforms.length; j++) {
  65767. var uniform = this._config.uniforms[j];
  65768. switch (uniform.type) {
  65769. case "float":
  65770. this.setFloat(uniform.name, uniform.value);
  65771. break;
  65772. case "color3":
  65773. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65774. break;
  65775. case "color4":
  65776. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65777. break;
  65778. case "vector2":
  65779. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65780. break;
  65781. case "vector3":
  65782. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65783. break;
  65784. }
  65785. }
  65786. }
  65787. this.setFloat("time", this._time);
  65788. };
  65789. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65790. get: function () {
  65791. return this._animate;
  65792. },
  65793. set: function (value) {
  65794. this._animate = value;
  65795. },
  65796. enumerable: true,
  65797. configurable: true
  65798. });
  65799. return CustomProceduralTexture;
  65800. }(BABYLON.ProceduralTexture));
  65801. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65802. })(BABYLON || (BABYLON = {}));
  65803. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65804. "use strict";
  65805. var BABYLON;
  65806. (function (BABYLON) {
  65807. var FreeCameraGamepadInput = /** @class */ (function () {
  65808. function FreeCameraGamepadInput() {
  65809. this.gamepadAngularSensibility = 200;
  65810. this.gamepadMoveSensibility = 40;
  65811. // private members
  65812. this._cameraTransform = BABYLON.Matrix.Identity();
  65813. this._deltaTransform = BABYLON.Vector3.Zero();
  65814. this._vector3 = BABYLON.Vector3.Zero();
  65815. this._vector2 = BABYLON.Vector2.Zero();
  65816. }
  65817. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65818. var _this = this;
  65819. var manager = this.camera.getScene().gamepadManager;
  65820. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65821. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65822. // prioritize XBOX gamepads.
  65823. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65824. _this.gamepad = gamepad;
  65825. }
  65826. }
  65827. });
  65828. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65829. if (_this.gamepad === gamepad) {
  65830. _this.gamepad = null;
  65831. }
  65832. });
  65833. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65834. };
  65835. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65836. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65837. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65838. this.gamepad = null;
  65839. };
  65840. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65841. if (this.gamepad && this.gamepad.leftStick) {
  65842. var camera = this.camera;
  65843. var LSValues = this.gamepad.leftStick;
  65844. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65845. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65846. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65847. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65848. var RSValues = this.gamepad.rightStick;
  65849. if (RSValues) {
  65850. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65851. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65852. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65853. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65854. }
  65855. else {
  65856. RSValues = { x: 0, y: 0 };
  65857. }
  65858. if (!camera.rotationQuaternion) {
  65859. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65860. }
  65861. else {
  65862. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65863. }
  65864. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65865. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65866. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65867. camera.cameraDirection.addInPlace(this._deltaTransform);
  65868. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65869. camera.cameraRotation.addInPlace(this._vector2);
  65870. }
  65871. };
  65872. FreeCameraGamepadInput.prototype.getClassName = function () {
  65873. return "FreeCameraGamepadInput";
  65874. };
  65875. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65876. return "gamepad";
  65877. };
  65878. __decorate([
  65879. BABYLON.serialize()
  65880. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65881. __decorate([
  65882. BABYLON.serialize()
  65883. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65884. return FreeCameraGamepadInput;
  65885. }());
  65886. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65887. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65888. })(BABYLON || (BABYLON = {}));
  65889. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65890. "use strict";
  65891. var BABYLON;
  65892. (function (BABYLON) {
  65893. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65894. function ArcRotateCameraGamepadInput() {
  65895. this.gamepadRotationSensibility = 80;
  65896. this.gamepadMoveSensibility = 40;
  65897. }
  65898. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65899. var _this = this;
  65900. var manager = this.camera.getScene().gamepadManager;
  65901. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65902. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65903. // prioritize XBOX gamepads.
  65904. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65905. _this.gamepad = gamepad;
  65906. }
  65907. }
  65908. });
  65909. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65910. if (_this.gamepad === gamepad) {
  65911. _this.gamepad = null;
  65912. }
  65913. });
  65914. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65915. };
  65916. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65917. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65918. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65919. this.gamepad = null;
  65920. };
  65921. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65922. if (this.gamepad) {
  65923. var camera = this.camera;
  65924. var RSValues = this.gamepad.rightStick;
  65925. if (RSValues) {
  65926. if (RSValues.x != 0) {
  65927. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65928. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65929. camera.inertialAlphaOffset += normalizedRX;
  65930. }
  65931. }
  65932. if (RSValues.y != 0) {
  65933. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65934. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65935. camera.inertialBetaOffset += normalizedRY;
  65936. }
  65937. }
  65938. }
  65939. var LSValues = this.gamepad.leftStick;
  65940. if (LSValues && LSValues.y != 0) {
  65941. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65942. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65943. this.camera.inertialRadiusOffset -= normalizedLY;
  65944. }
  65945. }
  65946. }
  65947. };
  65948. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65949. return "ArcRotateCameraGamepadInput";
  65950. };
  65951. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65952. return "gamepad";
  65953. };
  65954. __decorate([
  65955. BABYLON.serialize()
  65956. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65957. __decorate([
  65958. BABYLON.serialize()
  65959. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65960. return ArcRotateCameraGamepadInput;
  65961. }());
  65962. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65963. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65964. })(BABYLON || (BABYLON = {}));
  65965. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65966. "use strict";
  65967. var BABYLON;
  65968. (function (BABYLON) {
  65969. var GamepadManager = /** @class */ (function () {
  65970. function GamepadManager(_scene) {
  65971. var _this = this;
  65972. this._scene = _scene;
  65973. this._babylonGamepads = [];
  65974. this._oneGamepadConnected = false;
  65975. this._isMonitoring = false;
  65976. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65977. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65978. this._gamepadEventSupported = false;
  65979. }
  65980. else {
  65981. this._gamepadEventSupported = 'GamepadEvent' in window;
  65982. this._gamepadSupport = (navigator.getGamepads ||
  65983. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65984. }
  65985. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65986. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65987. for (var i in _this._babylonGamepads) {
  65988. var gamepad = _this._babylonGamepads[i];
  65989. if (gamepad && gamepad._isConnected) {
  65990. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65991. }
  65992. }
  65993. });
  65994. this._onGamepadConnectedEvent = function (evt) {
  65995. var gamepad = evt.gamepad;
  65996. if (gamepad.index in _this._babylonGamepads) {
  65997. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65998. return;
  65999. }
  66000. }
  66001. var newGamepad;
  66002. if (_this._babylonGamepads[gamepad.index]) {
  66003. newGamepad = _this._babylonGamepads[gamepad.index];
  66004. newGamepad.browserGamepad = gamepad;
  66005. newGamepad._isConnected = true;
  66006. }
  66007. else {
  66008. newGamepad = _this._addNewGamepad(gamepad);
  66009. }
  66010. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66011. _this._startMonitoringGamepads();
  66012. };
  66013. this._onGamepadDisconnectedEvent = function (evt) {
  66014. var gamepad = evt.gamepad;
  66015. // Remove the gamepad from the list of gamepads to monitor.
  66016. for (var i in _this._babylonGamepads) {
  66017. if (_this._babylonGamepads[i].index === gamepad.index) {
  66018. var disconnectedGamepad = _this._babylonGamepads[i];
  66019. disconnectedGamepad._isConnected = false;
  66020. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  66021. break;
  66022. }
  66023. }
  66024. };
  66025. if (this._gamepadSupport) {
  66026. //first add already-connected gamepads
  66027. this._updateGamepadObjects();
  66028. if (this._babylonGamepads.length) {
  66029. this._startMonitoringGamepads();
  66030. }
  66031. // Checking if the gamepad connected event is supported (like in Firefox)
  66032. if (this._gamepadEventSupported) {
  66033. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  66034. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  66035. }
  66036. else {
  66037. this._startMonitoringGamepads();
  66038. }
  66039. }
  66040. }
  66041. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  66042. get: function () {
  66043. return this._babylonGamepads;
  66044. },
  66045. enumerable: true,
  66046. configurable: true
  66047. });
  66048. GamepadManager.prototype.getGamepadByType = function (type) {
  66049. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  66050. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  66051. var gamepad = _a[_i];
  66052. if (gamepad && gamepad.type === type) {
  66053. return gamepad;
  66054. }
  66055. }
  66056. return null;
  66057. };
  66058. GamepadManager.prototype.dispose = function () {
  66059. if (this._gamepadEventSupported) {
  66060. if (this._onGamepadConnectedEvent) {
  66061. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  66062. }
  66063. if (this._onGamepadDisconnectedEvent) {
  66064. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  66065. }
  66066. this._onGamepadConnectedEvent = null;
  66067. this._onGamepadDisconnectedEvent = null;
  66068. }
  66069. this._babylonGamepads.forEach(function (gamepad) {
  66070. gamepad.dispose();
  66071. });
  66072. this.onGamepadConnectedObservable.clear();
  66073. this.onGamepadDisconnectedObservable.clear();
  66074. this._oneGamepadConnected = false;
  66075. this._stopMonitoringGamepads();
  66076. this._babylonGamepads = [];
  66077. };
  66078. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  66079. if (!this._oneGamepadConnected) {
  66080. this._oneGamepadConnected = true;
  66081. }
  66082. var newGamepad;
  66083. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  66084. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  66085. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  66086. }
  66087. else if (gamepad.pose) {
  66088. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  66089. }
  66090. else {
  66091. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  66092. }
  66093. this._babylonGamepads[newGamepad.index] = newGamepad;
  66094. return newGamepad;
  66095. };
  66096. GamepadManager.prototype._startMonitoringGamepads = function () {
  66097. if (!this._isMonitoring) {
  66098. this._isMonitoring = true;
  66099. //back-comp
  66100. if (!this._scene) {
  66101. this._checkGamepadsStatus();
  66102. }
  66103. }
  66104. };
  66105. GamepadManager.prototype._stopMonitoringGamepads = function () {
  66106. this._isMonitoring = false;
  66107. };
  66108. GamepadManager.prototype._checkGamepadsStatus = function () {
  66109. var _this = this;
  66110. // Hack to be compatible Chrome
  66111. this._updateGamepadObjects();
  66112. for (var i in this._babylonGamepads) {
  66113. var gamepad = this._babylonGamepads[i];
  66114. if (!gamepad || !gamepad.isConnected) {
  66115. continue;
  66116. }
  66117. gamepad.update();
  66118. }
  66119. if (this._isMonitoring && !this._scene) {
  66120. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  66121. }
  66122. };
  66123. // This function is called only on Chrome, which does not properly support
  66124. // connection/disconnection events and forces you to recopy again the gamepad object
  66125. GamepadManager.prototype._updateGamepadObjects = function () {
  66126. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  66127. for (var i = 0; i < gamepads.length; i++) {
  66128. if (gamepads[i]) {
  66129. if (!this._babylonGamepads[gamepads[i].index]) {
  66130. var newGamepad = this._addNewGamepad(gamepads[i]);
  66131. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66132. }
  66133. else {
  66134. // Forced to copy again this object for Chrome for unknown reason
  66135. this._babylonGamepads[i].browserGamepad = gamepads[i];
  66136. if (!this._babylonGamepads[i].isConnected) {
  66137. this._babylonGamepads[i]._isConnected = true;
  66138. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  66139. }
  66140. }
  66141. }
  66142. }
  66143. };
  66144. return GamepadManager;
  66145. }());
  66146. BABYLON.GamepadManager = GamepadManager;
  66147. })(BABYLON || (BABYLON = {}));
  66148. //# sourceMappingURL=babylon.gamepadManager.js.map
  66149. "use strict";
  66150. var BABYLON;
  66151. (function (BABYLON) {
  66152. var StickValues = /** @class */ (function () {
  66153. function StickValues(x, y) {
  66154. this.x = x;
  66155. this.y = y;
  66156. }
  66157. return StickValues;
  66158. }());
  66159. BABYLON.StickValues = StickValues;
  66160. var Gamepad = /** @class */ (function () {
  66161. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  66162. if (leftStickX === void 0) { leftStickX = 0; }
  66163. if (leftStickY === void 0) { leftStickY = 1; }
  66164. if (rightStickX === void 0) { rightStickX = 2; }
  66165. if (rightStickY === void 0) { rightStickY = 3; }
  66166. this.id = id;
  66167. this.index = index;
  66168. this.browserGamepad = browserGamepad;
  66169. this._isConnected = true;
  66170. this._invertLeftStickY = false;
  66171. this.type = Gamepad.GAMEPAD;
  66172. this._leftStickAxisX = leftStickX;
  66173. this._leftStickAxisY = leftStickY;
  66174. this._rightStickAxisX = rightStickX;
  66175. this._rightStickAxisY = rightStickY;
  66176. if (this.browserGamepad.axes.length >= 2) {
  66177. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66178. }
  66179. if (this.browserGamepad.axes.length >= 4) {
  66180. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66181. }
  66182. }
  66183. Object.defineProperty(Gamepad.prototype, "isConnected", {
  66184. get: function () {
  66185. return this._isConnected;
  66186. },
  66187. enumerable: true,
  66188. configurable: true
  66189. });
  66190. Gamepad.prototype.onleftstickchanged = function (callback) {
  66191. this._onleftstickchanged = callback;
  66192. };
  66193. Gamepad.prototype.onrightstickchanged = function (callback) {
  66194. this._onrightstickchanged = callback;
  66195. };
  66196. Object.defineProperty(Gamepad.prototype, "leftStick", {
  66197. get: function () {
  66198. return this._leftStick;
  66199. },
  66200. set: function (newValues) {
  66201. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  66202. this._onleftstickchanged(newValues);
  66203. }
  66204. this._leftStick = newValues;
  66205. },
  66206. enumerable: true,
  66207. configurable: true
  66208. });
  66209. Object.defineProperty(Gamepad.prototype, "rightStick", {
  66210. get: function () {
  66211. return this._rightStick;
  66212. },
  66213. set: function (newValues) {
  66214. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  66215. this._onrightstickchanged(newValues);
  66216. }
  66217. this._rightStick = newValues;
  66218. },
  66219. enumerable: true,
  66220. configurable: true
  66221. });
  66222. Gamepad.prototype.update = function () {
  66223. if (this._leftStick) {
  66224. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66225. if (this._invertLeftStickY) {
  66226. this.leftStick.y *= -1;
  66227. }
  66228. }
  66229. if (this._rightStick) {
  66230. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66231. }
  66232. };
  66233. Gamepad.prototype.dispose = function () {
  66234. };
  66235. Gamepad.GAMEPAD = 0;
  66236. Gamepad.GENERIC = 1;
  66237. Gamepad.XBOX = 2;
  66238. Gamepad.POSE_ENABLED = 3;
  66239. return Gamepad;
  66240. }());
  66241. BABYLON.Gamepad = Gamepad;
  66242. var GenericPad = /** @class */ (function (_super) {
  66243. __extends(GenericPad, _super);
  66244. function GenericPad(id, index, browserGamepad) {
  66245. var _this = _super.call(this, id, index, browserGamepad) || this;
  66246. _this.onButtonDownObservable = new BABYLON.Observable();
  66247. _this.onButtonUpObservable = new BABYLON.Observable();
  66248. _this.type = Gamepad.GENERIC;
  66249. _this._buttons = new Array(browserGamepad.buttons.length);
  66250. return _this;
  66251. }
  66252. GenericPad.prototype.onbuttondown = function (callback) {
  66253. this._onbuttondown = callback;
  66254. };
  66255. GenericPad.prototype.onbuttonup = function (callback) {
  66256. this._onbuttonup = callback;
  66257. };
  66258. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  66259. if (newValue !== currentValue) {
  66260. if (newValue === 1) {
  66261. if (this._onbuttondown) {
  66262. this._onbuttondown(buttonIndex);
  66263. }
  66264. this.onButtonDownObservable.notifyObservers(buttonIndex);
  66265. }
  66266. if (newValue === 0) {
  66267. if (this._onbuttonup) {
  66268. this._onbuttonup(buttonIndex);
  66269. }
  66270. this.onButtonUpObservable.notifyObservers(buttonIndex);
  66271. }
  66272. }
  66273. return newValue;
  66274. };
  66275. GenericPad.prototype.update = function () {
  66276. _super.prototype.update.call(this);
  66277. for (var index = 0; index < this._buttons.length; index++) {
  66278. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  66279. }
  66280. };
  66281. GenericPad.prototype.dispose = function () {
  66282. _super.prototype.dispose.call(this);
  66283. this.onButtonDownObservable.clear();
  66284. this.onButtonUpObservable.clear();
  66285. };
  66286. return GenericPad;
  66287. }(Gamepad));
  66288. BABYLON.GenericPad = GenericPad;
  66289. })(BABYLON || (BABYLON = {}));
  66290. //# sourceMappingURL=babylon.gamepad.js.map
  66291. "use strict";
  66292. var BABYLON;
  66293. (function (BABYLON) {
  66294. var Xbox360Button;
  66295. (function (Xbox360Button) {
  66296. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  66297. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  66298. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  66299. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  66300. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  66301. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  66302. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  66303. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  66304. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  66305. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  66306. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  66307. var Xbox360Dpad;
  66308. (function (Xbox360Dpad) {
  66309. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66310. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66311. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66312. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66313. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66314. var Xbox360Pad = /** @class */ (function (_super) {
  66315. __extends(Xbox360Pad, _super);
  66316. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66317. if (xboxOne === void 0) { xboxOne = false; }
  66318. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66319. _this._leftTrigger = 0;
  66320. _this._rightTrigger = 0;
  66321. _this.onButtonDownObservable = new BABYLON.Observable();
  66322. _this.onButtonUpObservable = new BABYLON.Observable();
  66323. _this.onPadDownObservable = new BABYLON.Observable();
  66324. _this.onPadUpObservable = new BABYLON.Observable();
  66325. _this._buttonA = 0;
  66326. _this._buttonB = 0;
  66327. _this._buttonX = 0;
  66328. _this._buttonY = 0;
  66329. _this._buttonBack = 0;
  66330. _this._buttonStart = 0;
  66331. _this._buttonLB = 0;
  66332. _this._buttonRB = 0;
  66333. _this._buttonLeftStick = 0;
  66334. _this._buttonRightStick = 0;
  66335. _this._dPadUp = 0;
  66336. _this._dPadDown = 0;
  66337. _this._dPadLeft = 0;
  66338. _this._dPadRight = 0;
  66339. _this._isXboxOnePad = false;
  66340. _this.type = BABYLON.Gamepad.XBOX;
  66341. _this._isXboxOnePad = xboxOne;
  66342. return _this;
  66343. }
  66344. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66345. this._onlefttriggerchanged = callback;
  66346. };
  66347. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66348. this._onrighttriggerchanged = callback;
  66349. };
  66350. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66351. get: function () {
  66352. return this._leftTrigger;
  66353. },
  66354. set: function (newValue) {
  66355. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66356. this._onlefttriggerchanged(newValue);
  66357. }
  66358. this._leftTrigger = newValue;
  66359. },
  66360. enumerable: true,
  66361. configurable: true
  66362. });
  66363. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66364. get: function () {
  66365. return this._rightTrigger;
  66366. },
  66367. set: function (newValue) {
  66368. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66369. this._onrighttriggerchanged(newValue);
  66370. }
  66371. this._rightTrigger = newValue;
  66372. },
  66373. enumerable: true,
  66374. configurable: true
  66375. });
  66376. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66377. this._onbuttondown = callback;
  66378. };
  66379. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66380. this._onbuttonup = callback;
  66381. };
  66382. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66383. this._ondpaddown = callback;
  66384. };
  66385. Xbox360Pad.prototype.ondpadup = function (callback) {
  66386. this._ondpadup = callback;
  66387. };
  66388. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66389. if (newValue !== currentValue) {
  66390. if (newValue === 1) {
  66391. if (this._onbuttondown) {
  66392. this._onbuttondown(buttonType);
  66393. }
  66394. this.onButtonDownObservable.notifyObservers(buttonType);
  66395. }
  66396. if (newValue === 0) {
  66397. if (this._onbuttonup) {
  66398. this._onbuttonup(buttonType);
  66399. }
  66400. this.onButtonUpObservable.notifyObservers(buttonType);
  66401. }
  66402. }
  66403. return newValue;
  66404. };
  66405. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66406. if (newValue !== currentValue) {
  66407. if (newValue === 1) {
  66408. if (this._ondpaddown) {
  66409. this._ondpaddown(buttonType);
  66410. }
  66411. this.onPadDownObservable.notifyObservers(buttonType);
  66412. }
  66413. if (newValue === 0) {
  66414. if (this._ondpadup) {
  66415. this._ondpadup(buttonType);
  66416. }
  66417. this.onPadUpObservable.notifyObservers(buttonType);
  66418. }
  66419. }
  66420. return newValue;
  66421. };
  66422. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66423. get: function () {
  66424. return this._buttonA;
  66425. },
  66426. set: function (value) {
  66427. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66428. },
  66429. enumerable: true,
  66430. configurable: true
  66431. });
  66432. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66433. get: function () {
  66434. return this._buttonB;
  66435. },
  66436. set: function (value) {
  66437. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66438. },
  66439. enumerable: true,
  66440. configurable: true
  66441. });
  66442. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66443. get: function () {
  66444. return this._buttonX;
  66445. },
  66446. set: function (value) {
  66447. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66448. },
  66449. enumerable: true,
  66450. configurable: true
  66451. });
  66452. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66453. get: function () {
  66454. return this._buttonY;
  66455. },
  66456. set: function (value) {
  66457. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66458. },
  66459. enumerable: true,
  66460. configurable: true
  66461. });
  66462. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66463. get: function () {
  66464. return this._buttonStart;
  66465. },
  66466. set: function (value) {
  66467. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66468. },
  66469. enumerable: true,
  66470. configurable: true
  66471. });
  66472. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66473. get: function () {
  66474. return this._buttonBack;
  66475. },
  66476. set: function (value) {
  66477. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66478. },
  66479. enumerable: true,
  66480. configurable: true
  66481. });
  66482. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66483. get: function () {
  66484. return this._buttonLB;
  66485. },
  66486. set: function (value) {
  66487. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66488. },
  66489. enumerable: true,
  66490. configurable: true
  66491. });
  66492. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66493. get: function () {
  66494. return this._buttonRB;
  66495. },
  66496. set: function (value) {
  66497. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66498. },
  66499. enumerable: true,
  66500. configurable: true
  66501. });
  66502. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66503. get: function () {
  66504. return this._buttonLeftStick;
  66505. },
  66506. set: function (value) {
  66507. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66508. },
  66509. enumerable: true,
  66510. configurable: true
  66511. });
  66512. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66513. get: function () {
  66514. return this._buttonRightStick;
  66515. },
  66516. set: function (value) {
  66517. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66518. },
  66519. enumerable: true,
  66520. configurable: true
  66521. });
  66522. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66523. get: function () {
  66524. return this._dPadUp;
  66525. },
  66526. set: function (value) {
  66527. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66528. },
  66529. enumerable: true,
  66530. configurable: true
  66531. });
  66532. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66533. get: function () {
  66534. return this._dPadDown;
  66535. },
  66536. set: function (value) {
  66537. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66538. },
  66539. enumerable: true,
  66540. configurable: true
  66541. });
  66542. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66543. get: function () {
  66544. return this._dPadLeft;
  66545. },
  66546. set: function (value) {
  66547. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66548. },
  66549. enumerable: true,
  66550. configurable: true
  66551. });
  66552. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66553. get: function () {
  66554. return this._dPadRight;
  66555. },
  66556. set: function (value) {
  66557. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66558. },
  66559. enumerable: true,
  66560. configurable: true
  66561. });
  66562. Xbox360Pad.prototype.update = function () {
  66563. _super.prototype.update.call(this);
  66564. if (this._isXboxOnePad) {
  66565. this.buttonA = this.browserGamepad.buttons[0].value;
  66566. this.buttonB = this.browserGamepad.buttons[1].value;
  66567. this.buttonX = this.browserGamepad.buttons[2].value;
  66568. this.buttonY = this.browserGamepad.buttons[3].value;
  66569. this.buttonLB = this.browserGamepad.buttons[4].value;
  66570. this.buttonRB = this.browserGamepad.buttons[5].value;
  66571. this.leftTrigger = this.browserGamepad.axes[2];
  66572. this.rightTrigger = this.browserGamepad.axes[5];
  66573. this.buttonBack = this.browserGamepad.buttons[9].value;
  66574. this.buttonStart = this.browserGamepad.buttons[8].value;
  66575. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66576. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66577. this.dPadUp = this.browserGamepad.buttons[11].value;
  66578. this.dPadDown = this.browserGamepad.buttons[12].value;
  66579. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66580. this.dPadRight = this.browserGamepad.buttons[14].value;
  66581. }
  66582. else {
  66583. this.buttonA = this.browserGamepad.buttons[0].value;
  66584. this.buttonB = this.browserGamepad.buttons[1].value;
  66585. this.buttonX = this.browserGamepad.buttons[2].value;
  66586. this.buttonY = this.browserGamepad.buttons[3].value;
  66587. this.buttonLB = this.browserGamepad.buttons[4].value;
  66588. this.buttonRB = this.browserGamepad.buttons[5].value;
  66589. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66590. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66591. this.buttonBack = this.browserGamepad.buttons[8].value;
  66592. this.buttonStart = this.browserGamepad.buttons[9].value;
  66593. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66594. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66595. this.dPadUp = this.browserGamepad.buttons[12].value;
  66596. this.dPadDown = this.browserGamepad.buttons[13].value;
  66597. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66598. this.dPadRight = this.browserGamepad.buttons[15].value;
  66599. }
  66600. };
  66601. Xbox360Pad.prototype.dispose = function () {
  66602. _super.prototype.dispose.call(this);
  66603. this.onButtonDownObservable.clear();
  66604. this.onButtonUpObservable.clear();
  66605. this.onPadDownObservable.clear();
  66606. this.onPadUpObservable.clear();
  66607. };
  66608. return Xbox360Pad;
  66609. }(BABYLON.Gamepad));
  66610. BABYLON.Xbox360Pad = Xbox360Pad;
  66611. })(BABYLON || (BABYLON = {}));
  66612. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66613. "use strict";
  66614. var BABYLON;
  66615. (function (BABYLON) {
  66616. var PoseEnabledControllerType;
  66617. (function (PoseEnabledControllerType) {
  66618. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66619. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66620. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66621. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66622. /**
  66623. * Google Daydream
  66624. */
  66625. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66626. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66627. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66628. var PoseEnabledControllerHelper = /** @class */ (function () {
  66629. function PoseEnabledControllerHelper() {
  66630. }
  66631. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66632. // Oculus Touch
  66633. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66634. return new BABYLON.OculusTouchController(vrGamepad);
  66635. }
  66636. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66637. return new BABYLON.WindowsMotionController(vrGamepad);
  66638. }
  66639. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66640. return new BABYLON.ViveController(vrGamepad);
  66641. }
  66642. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66643. return new BABYLON.GearVRController(vrGamepad);
  66644. }
  66645. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66646. return new BABYLON.DaydreamController(vrGamepad);
  66647. }
  66648. else {
  66649. return new BABYLON.GenericController(vrGamepad);
  66650. }
  66651. };
  66652. return PoseEnabledControllerHelper;
  66653. }());
  66654. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66655. var PoseEnabledController = /** @class */ (function (_super) {
  66656. __extends(PoseEnabledController, _super);
  66657. function PoseEnabledController(browserGamepad) {
  66658. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66659. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66660. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66661. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66662. // Represents device position and rotation in babylon space
  66663. _this.devicePosition = BABYLON.Vector3.Zero();
  66664. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66665. _this.deviceScaleFactor = 1;
  66666. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66667. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66668. /**
  66669. * Node to be used when casting a ray from the controller
  66670. */
  66671. _this._pointingPoseNode = null;
  66672. _this._workingMatrix = BABYLON.Matrix.Identity();
  66673. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66674. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66675. _this.position = BABYLON.Vector3.Zero();
  66676. _this.rotationQuaternion = new BABYLON.Quaternion();
  66677. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66678. _this._calculatedRotation = new BABYLON.Quaternion();
  66679. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66680. return _this;
  66681. }
  66682. PoseEnabledController.prototype.update = function () {
  66683. _super.prototype.update.call(this);
  66684. var pose = this.browserGamepad.pose;
  66685. this.updateFromDevice(pose);
  66686. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66687. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66688. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66689. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66690. if (this._mesh) {
  66691. this._mesh.position.copyFrom(this.devicePosition);
  66692. if (this._mesh.rotationQuaternion) {
  66693. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66694. }
  66695. }
  66696. };
  66697. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66698. if (poseData) {
  66699. this.rawPose = poseData;
  66700. if (poseData.position) {
  66701. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66702. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66703. this._deviceRoomPosition.z *= -1;
  66704. }
  66705. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66706. this._calculatedPosition.addInPlace(this.position);
  66707. }
  66708. var pose = this.rawPose;
  66709. if (poseData.orientation && pose.orientation) {
  66710. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66711. if (this._mesh) {
  66712. if (this._mesh.getScene().useRightHandedSystem) {
  66713. this._deviceRoomRotationQuaternion.z *= -1;
  66714. this._deviceRoomRotationQuaternion.w *= -1;
  66715. }
  66716. else {
  66717. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66718. }
  66719. }
  66720. // if the camera is set, rotate to the camera's rotation
  66721. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66722. }
  66723. }
  66724. };
  66725. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66726. if (this._mesh) {
  66727. this._mesh.parent = null;
  66728. }
  66729. this._mesh = mesh;
  66730. if (this._poseControlledCamera) {
  66731. this._mesh.parent = this._poseControlledCamera;
  66732. }
  66733. if (!this._mesh.rotationQuaternion) {
  66734. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66735. }
  66736. };
  66737. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66738. this._poseControlledCamera = camera;
  66739. if (this._mesh) {
  66740. this._mesh.parent = this._poseControlledCamera;
  66741. }
  66742. };
  66743. PoseEnabledController.prototype.dispose = function () {
  66744. if (this._mesh) {
  66745. this._mesh.dispose();
  66746. }
  66747. this._mesh = null;
  66748. _super.prototype.dispose.call(this);
  66749. };
  66750. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66751. get: function () {
  66752. return this._mesh;
  66753. },
  66754. enumerable: true,
  66755. configurable: true
  66756. });
  66757. PoseEnabledController.prototype.getForwardRay = function (length) {
  66758. if (length === void 0) { length = 100; }
  66759. if (!this.mesh) {
  66760. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66761. }
  66762. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66763. var origin = m.getTranslation();
  66764. var forward = new BABYLON.Vector3(0, 0, -1);
  66765. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66766. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66767. return new BABYLON.Ray(origin, direction, length);
  66768. };
  66769. /**
  66770. * Name of the child mesh that can be used to cast a ray from the controller
  66771. */
  66772. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66773. return PoseEnabledController;
  66774. }(BABYLON.Gamepad));
  66775. BABYLON.PoseEnabledController = PoseEnabledController;
  66776. })(BABYLON || (BABYLON = {}));
  66777. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66778. "use strict";
  66779. var BABYLON;
  66780. (function (BABYLON) {
  66781. var WebVRController = /** @class */ (function (_super) {
  66782. __extends(WebVRController, _super);
  66783. function WebVRController(vrGamepad) {
  66784. var _this = _super.call(this, vrGamepad) || this;
  66785. // Observables
  66786. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66787. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66788. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66789. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66790. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66791. _this.pad = { x: 0, y: 0 };
  66792. // avoid GC, store state in a tmp object
  66793. _this._changes = {
  66794. pressChanged: false,
  66795. touchChanged: false,
  66796. valueChanged: false,
  66797. changed: false
  66798. };
  66799. _this._buttons = new Array(vrGamepad.buttons.length);
  66800. _this.hand = vrGamepad.hand;
  66801. return _this;
  66802. }
  66803. WebVRController.prototype.onButtonStateChange = function (callback) {
  66804. this._onButtonStateChange = callback;
  66805. };
  66806. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66807. get: function () {
  66808. return this._defaultModel;
  66809. },
  66810. enumerable: true,
  66811. configurable: true
  66812. });
  66813. WebVRController.prototype.update = function () {
  66814. _super.prototype.update.call(this);
  66815. for (var index = 0; index < this._buttons.length; index++) {
  66816. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66817. }
  66818. ;
  66819. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66820. this.pad.x = this.leftStick.x;
  66821. this.pad.y = this.leftStick.y;
  66822. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66823. }
  66824. };
  66825. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66826. if (!newState) {
  66827. newState = {
  66828. pressed: false,
  66829. touched: false,
  66830. value: 0
  66831. };
  66832. }
  66833. if (!currentState) {
  66834. this._buttons[buttonIndex] = {
  66835. pressed: newState.pressed,
  66836. touched: newState.touched,
  66837. value: newState.value
  66838. };
  66839. return;
  66840. }
  66841. this._checkChanges(newState, currentState);
  66842. if (this._changes.changed) {
  66843. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66844. this._handleButtonChange(buttonIndex, newState, this._changes);
  66845. }
  66846. this._buttons[buttonIndex].pressed = newState.pressed;
  66847. this._buttons[buttonIndex].touched = newState.touched;
  66848. // oculus triggers are never 0, thou not touched.
  66849. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66850. };
  66851. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66852. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66853. this._changes.touchChanged = newState.touched !== currentState.touched;
  66854. this._changes.valueChanged = newState.value !== currentState.value;
  66855. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66856. return this._changes;
  66857. };
  66858. WebVRController.prototype.dispose = function () {
  66859. _super.prototype.dispose.call(this);
  66860. this.onTriggerStateChangedObservable.clear();
  66861. this.onMainButtonStateChangedObservable.clear();
  66862. this.onSecondaryButtonStateChangedObservable.clear();
  66863. this.onPadStateChangedObservable.clear();
  66864. this.onPadValuesChangedObservable.clear();
  66865. };
  66866. return WebVRController;
  66867. }(BABYLON.PoseEnabledController));
  66868. BABYLON.WebVRController = WebVRController;
  66869. })(BABYLON || (BABYLON = {}));
  66870. //# sourceMappingURL=babylon.webVRController.js.map
  66871. "use strict";
  66872. var BABYLON;
  66873. (function (BABYLON) {
  66874. var OculusTouchController = /** @class */ (function (_super) {
  66875. __extends(OculusTouchController, _super);
  66876. function OculusTouchController(vrGamepad) {
  66877. var _this = _super.call(this, vrGamepad) || this;
  66878. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66879. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66880. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66881. return _this;
  66882. }
  66883. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66884. var _this = this;
  66885. var meshName;
  66886. // Hand
  66887. if (this.hand === 'left') {
  66888. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66889. }
  66890. else {
  66891. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66892. }
  66893. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66894. /*
  66895. Parent Mesh name: oculus_touch_left
  66896. - body
  66897. - trigger
  66898. - thumbstick
  66899. - grip
  66900. - button_y
  66901. - button_x
  66902. - button_enter
  66903. */
  66904. _this._defaultModel = newMeshes[1];
  66905. _this.attachToMesh(_this._defaultModel);
  66906. if (meshLoaded) {
  66907. meshLoaded(_this._defaultModel);
  66908. }
  66909. });
  66910. };
  66911. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66912. // helper getters for left and right hand.
  66913. get: function () {
  66914. if (this.hand === 'right') {
  66915. return this.onMainButtonStateChangedObservable;
  66916. }
  66917. else {
  66918. throw new Error('No A button on left hand');
  66919. }
  66920. },
  66921. enumerable: true,
  66922. configurable: true
  66923. });
  66924. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66925. get: function () {
  66926. if (this.hand === 'right') {
  66927. return this.onSecondaryButtonStateChangedObservable;
  66928. }
  66929. else {
  66930. throw new Error('No B button on left hand');
  66931. }
  66932. },
  66933. enumerable: true,
  66934. configurable: true
  66935. });
  66936. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66937. get: function () {
  66938. if (this.hand === 'left') {
  66939. return this.onMainButtonStateChangedObservable;
  66940. }
  66941. else {
  66942. throw new Error('No X button on right hand');
  66943. }
  66944. },
  66945. enumerable: true,
  66946. configurable: true
  66947. });
  66948. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66949. get: function () {
  66950. if (this.hand === 'left') {
  66951. return this.onSecondaryButtonStateChangedObservable;
  66952. }
  66953. else {
  66954. throw new Error('No Y button on right hand');
  66955. }
  66956. },
  66957. enumerable: true,
  66958. configurable: true
  66959. });
  66960. /*
  66961. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66962. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66963. 2) secondary trigger (same)
  66964. 3) A (right) X (left), touch, pressed = value
  66965. 4) B / Y
  66966. 5) thumb rest
  66967. */
  66968. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66969. var notifyObject = state; //{ state: state, changes: changes };
  66970. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66971. switch (buttonIdx) {
  66972. case 0:
  66973. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66974. return;
  66975. case 1:// index trigger
  66976. if (this._defaultModel) {
  66977. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66978. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66979. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66980. }
  66981. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66982. return;
  66983. case 2:// secondary trigger
  66984. if (this._defaultModel) {
  66985. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66986. }
  66987. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66988. return;
  66989. case 3:
  66990. if (this._defaultModel) {
  66991. if (notifyObject.pressed) {
  66992. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66993. }
  66994. else {
  66995. (this._defaultModel.getChildren()[1]).position.y = 0;
  66996. }
  66997. }
  66998. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66999. return;
  67000. case 4:
  67001. if (this._defaultModel) {
  67002. if (notifyObject.pressed) {
  67003. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67004. }
  67005. else {
  67006. (this._defaultModel.getChildren()[2]).position.y = 0;
  67007. }
  67008. }
  67009. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67010. return;
  67011. case 5:
  67012. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  67013. return;
  67014. }
  67015. };
  67016. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  67017. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  67018. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  67019. return OculusTouchController;
  67020. }(BABYLON.WebVRController));
  67021. BABYLON.OculusTouchController = OculusTouchController;
  67022. })(BABYLON || (BABYLON = {}));
  67023. //# sourceMappingURL=babylon.oculusTouchController.js.map
  67024. "use strict";
  67025. var BABYLON;
  67026. (function (BABYLON) {
  67027. var ViveController = /** @class */ (function (_super) {
  67028. __extends(ViveController, _super);
  67029. function ViveController(vrGamepad) {
  67030. var _this = _super.call(this, vrGamepad) || this;
  67031. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  67032. _this._invertLeftStickY = true;
  67033. return _this;
  67034. }
  67035. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67036. var _this = this;
  67037. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  67038. /*
  67039. Parent Mesh name: ViveWand
  67040. - body
  67041. - r_gripper
  67042. - l_gripper
  67043. - menu_button
  67044. - system_button
  67045. - trackpad
  67046. - trigger
  67047. - LED
  67048. */
  67049. _this._defaultModel = newMeshes[1];
  67050. _this.attachToMesh(_this._defaultModel);
  67051. if (meshLoaded) {
  67052. meshLoaded(_this._defaultModel);
  67053. }
  67054. });
  67055. };
  67056. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  67057. get: function () {
  67058. return this.onMainButtonStateChangedObservable;
  67059. },
  67060. enumerable: true,
  67061. configurable: true
  67062. });
  67063. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  67064. get: function () {
  67065. return this.onMainButtonStateChangedObservable;
  67066. },
  67067. enumerable: true,
  67068. configurable: true
  67069. });
  67070. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  67071. get: function () {
  67072. return this.onSecondaryButtonStateChangedObservable;
  67073. },
  67074. enumerable: true,
  67075. configurable: true
  67076. });
  67077. /**
  67078. * Vive mapping:
  67079. * 0: touchpad
  67080. * 1: trigger
  67081. * 2: left AND right buttons
  67082. * 3: menu button
  67083. */
  67084. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67085. var notifyObject = state; //{ state: state, changes: changes };
  67086. switch (buttonIdx) {
  67087. case 0:
  67088. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67089. return;
  67090. case 1:// index trigger
  67091. if (this._defaultModel) {
  67092. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  67093. }
  67094. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67095. return;
  67096. case 2:// left AND right button
  67097. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67098. return;
  67099. case 3:
  67100. if (this._defaultModel) {
  67101. if (notifyObject.pressed) {
  67102. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67103. }
  67104. else {
  67105. (this._defaultModel.getChildren()[2]).position.y = 0;
  67106. }
  67107. }
  67108. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67109. return;
  67110. }
  67111. };
  67112. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  67113. ViveController.MODEL_FILENAME = 'wand.babylon';
  67114. return ViveController;
  67115. }(BABYLON.WebVRController));
  67116. BABYLON.ViveController = ViveController;
  67117. })(BABYLON || (BABYLON = {}));
  67118. //# sourceMappingURL=babylon.viveController.js.map
  67119. "use strict";
  67120. var BABYLON;
  67121. (function (BABYLON) {
  67122. var GenericController = /** @class */ (function (_super) {
  67123. __extends(GenericController, _super);
  67124. function GenericController(vrGamepad) {
  67125. return _super.call(this, vrGamepad) || this;
  67126. }
  67127. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67128. var _this = this;
  67129. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  67130. _this._defaultModel = newMeshes[1];
  67131. _this.attachToMesh(_this._defaultModel);
  67132. if (meshLoaded) {
  67133. meshLoaded(_this._defaultModel);
  67134. }
  67135. });
  67136. };
  67137. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67138. console.log("Button id: " + buttonIdx + "state: ");
  67139. console.dir(state);
  67140. };
  67141. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67142. GenericController.MODEL_FILENAME = 'generic.babylon';
  67143. return GenericController;
  67144. }(BABYLON.WebVRController));
  67145. BABYLON.GenericController = GenericController;
  67146. })(BABYLON || (BABYLON = {}));
  67147. //# sourceMappingURL=babylon.genericController.js.map
  67148. "use strict";
  67149. var BABYLON;
  67150. (function (BABYLON) {
  67151. var LoadedMeshInfo = /** @class */ (function () {
  67152. function LoadedMeshInfo() {
  67153. this.buttonMeshes = {};
  67154. this.axisMeshes = {};
  67155. }
  67156. return LoadedMeshInfo;
  67157. }());
  67158. var WindowsMotionController = /** @class */ (function (_super) {
  67159. __extends(WindowsMotionController, _super);
  67160. function WindowsMotionController(vrGamepad) {
  67161. var _this = _super.call(this, vrGamepad) || this;
  67162. _this._mapping = {
  67163. // Semantic button names
  67164. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  67165. // A mapping of the button name to glTF model node name
  67166. // that should be transformed by button value.
  67167. buttonMeshNames: {
  67168. 'trigger': 'SELECT',
  67169. 'menu': 'MENU',
  67170. 'grip': 'GRASP',
  67171. 'thumbstick': 'THUMBSTICK_PRESS',
  67172. 'trackpad': 'TOUCHPAD_PRESS'
  67173. },
  67174. // This mapping is used to translate from the Motion Controller to Babylon semantics
  67175. buttonObservableNames: {
  67176. 'trigger': 'onTriggerStateChangedObservable',
  67177. 'menu': 'onSecondaryButtonStateChangedObservable',
  67178. 'grip': 'onMainButtonStateChangedObservable',
  67179. 'thumbstick': 'onPadStateChangedObservable',
  67180. 'trackpad': 'onTrackpadChangedObservable'
  67181. },
  67182. // A mapping of the axis name to glTF model node name
  67183. // that should be transformed by axis value.
  67184. // This array mirrors the browserGamepad.axes array, such that
  67185. // the mesh corresponding to axis 0 is in this array index 0.
  67186. axisMeshNames: [
  67187. 'THUMBSTICK_X',
  67188. 'THUMBSTICK_Y',
  67189. 'TOUCHPAD_TOUCH_X',
  67190. 'TOUCHPAD_TOUCH_Y'
  67191. ],
  67192. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  67193. };
  67194. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  67195. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  67196. _this.trackpad = { x: 0, y: 0 };
  67197. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  67198. _this._loadedMeshInfo = null;
  67199. return _this;
  67200. }
  67201. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  67202. get: function () {
  67203. return this.onTriggerStateChangedObservable;
  67204. },
  67205. enumerable: true,
  67206. configurable: true
  67207. });
  67208. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  67209. get: function () {
  67210. return this.onSecondaryButtonStateChangedObservable;
  67211. },
  67212. enumerable: true,
  67213. configurable: true
  67214. });
  67215. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  67216. get: function () {
  67217. return this.onMainButtonStateChangedObservable;
  67218. },
  67219. enumerable: true,
  67220. configurable: true
  67221. });
  67222. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  67223. get: function () {
  67224. return this.onPadStateChangedObservable;
  67225. },
  67226. enumerable: true,
  67227. configurable: true
  67228. });
  67229. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  67230. get: function () {
  67231. return this.onTrackpadChangedObservable;
  67232. },
  67233. enumerable: true,
  67234. configurable: true
  67235. });
  67236. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  67237. get: function () {
  67238. return this.onTrackpadValuesChangedObservable;
  67239. },
  67240. enumerable: true,
  67241. configurable: true
  67242. });
  67243. /**
  67244. * Called once per frame by the engine.
  67245. */
  67246. WindowsMotionController.prototype.update = function () {
  67247. _super.prototype.update.call(this);
  67248. if (this.browserGamepad.axes) {
  67249. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  67250. this.trackpad.x = this.browserGamepad["axes"][2];
  67251. this.trackpad.y = this.browserGamepad["axes"][3];
  67252. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  67253. }
  67254. // Only need to animate axes if there is a loaded mesh
  67255. if (this._loadedMeshInfo) {
  67256. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  67257. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  67258. }
  67259. }
  67260. }
  67261. };
  67262. /**
  67263. * Called once for each button that changed state since the last frame
  67264. * @param buttonIdx Which button index changed
  67265. * @param state New state of the button
  67266. * @param changes Which properties on the state changed since last frame
  67267. */
  67268. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67269. var buttonName = this._mapping.buttons[buttonIdx];
  67270. if (!buttonName) {
  67271. return;
  67272. }
  67273. // Only emit events for buttons that we know how to map from index to name
  67274. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  67275. if (observable) {
  67276. observable.notifyObservers(state);
  67277. }
  67278. this.lerpButtonTransform(buttonName, state.value);
  67279. };
  67280. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  67281. // If there is no loaded mesh, there is nothing to transform.
  67282. if (!this._loadedMeshInfo) {
  67283. return;
  67284. }
  67285. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  67286. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67287. return;
  67288. }
  67289. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  67290. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  67291. };
  67292. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  67293. if (!this._loadedMeshInfo) {
  67294. return;
  67295. }
  67296. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  67297. if (!meshInfo) {
  67298. return;
  67299. }
  67300. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67301. return;
  67302. }
  67303. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  67304. var lerpValue = axisValue * 0.5 + 0.5;
  67305. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  67306. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  67307. };
  67308. /**
  67309. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67310. * @param scene scene in which to add meshes
  67311. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67312. */
  67313. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67314. var _this = this;
  67315. if (forceDefault === void 0) { forceDefault = false; }
  67316. var path;
  67317. var filename;
  67318. // Checking if GLB loader is present
  67319. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67320. // Determine the device specific folder based on the ID suffix
  67321. var device = 'default';
  67322. if (this.id && !forceDefault) {
  67323. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67324. device = ((match && match[0]) || device);
  67325. }
  67326. // Hand
  67327. if (this.hand === 'left') {
  67328. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67329. }
  67330. else {
  67331. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67332. }
  67333. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67334. }
  67335. else {
  67336. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67337. path = BABYLON.GenericController.MODEL_BASE_URL;
  67338. filename = BABYLON.GenericController.MODEL_FILENAME;
  67339. }
  67340. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67341. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67342. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67343. if (!_this._loadedMeshInfo) {
  67344. return;
  67345. }
  67346. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67347. _this.attachToMesh(_this._defaultModel);
  67348. if (meshLoaded) {
  67349. meshLoaded(_this._defaultModel);
  67350. }
  67351. }, null, function (scene, message) {
  67352. BABYLON.Tools.Log(message);
  67353. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67354. if (!forceDefault) {
  67355. _this.initControllerMesh(scene, meshLoaded, true);
  67356. }
  67357. });
  67358. };
  67359. /**
  67360. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67361. * can be transformed by button presses and axes values, based on this._mapping.
  67362. *
  67363. * @param scene scene in which the meshes exist
  67364. * @param meshes list of meshes that make up the controller model to process
  67365. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67366. */
  67367. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67368. var loadedMeshInfo = null;
  67369. // Create a new mesh to contain the glTF hierarchy
  67370. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67371. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67372. var childMesh = null;
  67373. for (var i = 0; i < meshes.length; i++) {
  67374. var mesh = meshes[i];
  67375. if (!mesh.parent) {
  67376. // Exclude controller meshes from picking results
  67377. mesh.isPickable = false;
  67378. // Handle root node, attach to the new parentMesh
  67379. childMesh = mesh;
  67380. break;
  67381. }
  67382. }
  67383. if (childMesh) {
  67384. childMesh.setParent(parentMesh);
  67385. // Create our mesh info. Note that this method will always return non-null.
  67386. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67387. }
  67388. else {
  67389. BABYLON.Tools.Warn('Could not find root node in model file.');
  67390. }
  67391. return loadedMeshInfo;
  67392. };
  67393. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67394. var loadedMeshInfo = new LoadedMeshInfo();
  67395. var i;
  67396. loadedMeshInfo.rootNode = rootNode;
  67397. // Reset the caches
  67398. loadedMeshInfo.buttonMeshes = {};
  67399. loadedMeshInfo.axisMeshes = {};
  67400. // Button Meshes
  67401. for (i = 0; i < this._mapping.buttons.length; i++) {
  67402. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67403. if (!buttonMeshName) {
  67404. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67405. continue;
  67406. }
  67407. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67408. if (!buttonMesh) {
  67409. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67410. continue;
  67411. }
  67412. var buttonMeshInfo = {
  67413. index: i,
  67414. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67415. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67416. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67417. };
  67418. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67419. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67420. }
  67421. else {
  67422. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67423. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67424. '(VALUE: ' + !!buttonMeshInfo.value +
  67425. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67426. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67427. ')');
  67428. }
  67429. }
  67430. // Axis Meshes
  67431. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67432. var axisMeshName = this._mapping.axisMeshNames[i];
  67433. if (!axisMeshName) {
  67434. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67435. continue;
  67436. }
  67437. var axisMesh = getChildByName(rootNode, axisMeshName);
  67438. if (!axisMesh) {
  67439. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67440. continue;
  67441. }
  67442. var axisMeshInfo = {
  67443. index: i,
  67444. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67445. min: getImmediateChildByName(axisMesh, 'MIN'),
  67446. max: getImmediateChildByName(axisMesh, 'MAX')
  67447. };
  67448. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67449. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67450. }
  67451. else {
  67452. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67453. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67454. '(VALUE: ' + !!axisMeshInfo.value +
  67455. ', MIN: ' + !!axisMeshInfo.min +
  67456. ', MAX:' + !!axisMeshInfo.max +
  67457. ')');
  67458. }
  67459. }
  67460. // Pointing Ray
  67461. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67462. if (!loadedMeshInfo.pointingPoseNode) {
  67463. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67464. }
  67465. return loadedMeshInfo;
  67466. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67467. function getChildByName(node, name) {
  67468. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67469. }
  67470. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67471. function getImmediateChildByName(node, name) {
  67472. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67473. }
  67474. };
  67475. WindowsMotionController.prototype.getForwardRay = function (length) {
  67476. if (length === void 0) { length = 100; }
  67477. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67478. return _super.prototype.getForwardRay.call(this, length);
  67479. }
  67480. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67481. var origin = m.getTranslation();
  67482. var forward = new BABYLON.Vector3(0, 0, -1);
  67483. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67484. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67485. return new BABYLON.Ray(origin, direction, length);
  67486. };
  67487. WindowsMotionController.prototype.dispose = function () {
  67488. _super.prototype.dispose.call(this);
  67489. this.onTrackpadChangedObservable.clear();
  67490. };
  67491. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67492. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67493. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67494. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67495. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67496. return WindowsMotionController;
  67497. }(BABYLON.WebVRController));
  67498. BABYLON.WindowsMotionController = WindowsMotionController;
  67499. })(BABYLON || (BABYLON = {}));
  67500. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67501. "use strict";
  67502. var BABYLON;
  67503. (function (BABYLON) {
  67504. var GearVRController = /** @class */ (function (_super) {
  67505. __extends(GearVRController, _super);
  67506. function GearVRController(vrGamepad) {
  67507. var _this = _super.call(this, vrGamepad) || this;
  67508. _this._buttonIndexToObservableNameMap = [
  67509. 'onTrackpadChangedObservable',
  67510. 'onTriggerStateChangedObservable' // Trigger
  67511. ];
  67512. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67513. return _this;
  67514. }
  67515. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67516. var _this = this;
  67517. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67518. _this._defaultModel = newMeshes[1];
  67519. _this.attachToMesh(_this._defaultModel);
  67520. if (meshLoaded) {
  67521. meshLoaded(_this._defaultModel);
  67522. }
  67523. });
  67524. };
  67525. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67526. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67527. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67528. // Only emit events for buttons that we know how to map from index to observable
  67529. var observable = this[observableName];
  67530. if (observable) {
  67531. observable.notifyObservers(state);
  67532. }
  67533. }
  67534. };
  67535. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67536. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67537. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67538. return GearVRController;
  67539. }(BABYLON.WebVRController));
  67540. BABYLON.GearVRController = GearVRController;
  67541. })(BABYLON || (BABYLON = {}));
  67542. //# sourceMappingURL=babylon.gearVRController.js.map
  67543. "use strict";
  67544. var BABYLON;
  67545. (function (BABYLON) {
  67546. /**
  67547. * Google Daydream controller
  67548. */
  67549. var DaydreamController = /** @class */ (function (_super) {
  67550. __extends(DaydreamController, _super);
  67551. function DaydreamController(vrGamepad) {
  67552. var _this = _super.call(this, vrGamepad) || this;
  67553. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67554. return _this;
  67555. }
  67556. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67557. var _this = this;
  67558. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67559. _this._defaultModel = newMeshes[1];
  67560. _this.attachToMesh(_this._defaultModel);
  67561. if (meshLoaded) {
  67562. meshLoaded(_this._defaultModel);
  67563. }
  67564. });
  67565. };
  67566. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67567. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67568. if (buttonIdx === 0) {
  67569. var observable = this.onTriggerStateChangedObservable;
  67570. if (observable) {
  67571. observable.notifyObservers(state);
  67572. }
  67573. }
  67574. else {
  67575. // If the app or home buttons are ever made available
  67576. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67577. }
  67578. };
  67579. /**
  67580. * Base Url for the controller model.
  67581. */
  67582. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67583. /**
  67584. * File name for the controller model.
  67585. */
  67586. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67587. /**
  67588. * Gamepad Id prefix used to identify Daydream Controller.
  67589. */
  67590. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67591. return DaydreamController;
  67592. }(BABYLON.WebVRController));
  67593. BABYLON.DaydreamController = DaydreamController;
  67594. })(BABYLON || (BABYLON = {}));
  67595. //# sourceMappingURL=babylon.daydreamController.js.map
  67596. "use strict";
  67597. var BABYLON;
  67598. (function (BABYLON) {
  67599. var FollowCamera = /** @class */ (function (_super) {
  67600. __extends(FollowCamera, _super);
  67601. function FollowCamera(name, position, scene, lockedTarget) {
  67602. if (lockedTarget === void 0) { lockedTarget = null; }
  67603. var _this = _super.call(this, name, position, scene) || this;
  67604. _this.radius = 12;
  67605. _this.rotationOffset = 0;
  67606. _this.heightOffset = 4;
  67607. _this.cameraAcceleration = 0.05;
  67608. _this.maxCameraSpeed = 20;
  67609. _this.lockedTarget = lockedTarget;
  67610. return _this;
  67611. }
  67612. FollowCamera.prototype.getRadians = function (degrees) {
  67613. return degrees * Math.PI / 180;
  67614. };
  67615. FollowCamera.prototype.follow = function (cameraTarget) {
  67616. if (!cameraTarget)
  67617. return;
  67618. var yRotation;
  67619. if (cameraTarget.rotationQuaternion) {
  67620. var rotMatrix = new BABYLON.Matrix();
  67621. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67622. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67623. }
  67624. else {
  67625. yRotation = cameraTarget.rotation.y;
  67626. }
  67627. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67628. var targetPosition = cameraTarget.getAbsolutePosition();
  67629. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67630. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67631. var dx = targetX - this.position.x;
  67632. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67633. var dz = (targetZ) - this.position.z;
  67634. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67635. var vy = dy * this.cameraAcceleration;
  67636. var vz = dz * this.cameraAcceleration * 2;
  67637. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67638. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67639. }
  67640. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67641. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67642. }
  67643. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67644. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67645. }
  67646. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67647. this.setTarget(targetPosition);
  67648. };
  67649. FollowCamera.prototype._checkInputs = function () {
  67650. _super.prototype._checkInputs.call(this);
  67651. if (this.lockedTarget) {
  67652. this.follow(this.lockedTarget);
  67653. }
  67654. };
  67655. FollowCamera.prototype.getClassName = function () {
  67656. return "FollowCamera";
  67657. };
  67658. __decorate([
  67659. BABYLON.serialize()
  67660. ], FollowCamera.prototype, "radius", void 0);
  67661. __decorate([
  67662. BABYLON.serialize()
  67663. ], FollowCamera.prototype, "rotationOffset", void 0);
  67664. __decorate([
  67665. BABYLON.serialize()
  67666. ], FollowCamera.prototype, "heightOffset", void 0);
  67667. __decorate([
  67668. BABYLON.serialize()
  67669. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67670. __decorate([
  67671. BABYLON.serialize()
  67672. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67673. __decorate([
  67674. BABYLON.serializeAsMeshReference("lockedTargetId")
  67675. ], FollowCamera.prototype, "lockedTarget", void 0);
  67676. return FollowCamera;
  67677. }(BABYLON.TargetCamera));
  67678. BABYLON.FollowCamera = FollowCamera;
  67679. var ArcFollowCamera = /** @class */ (function (_super) {
  67680. __extends(ArcFollowCamera, _super);
  67681. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67682. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67683. _this.alpha = alpha;
  67684. _this.beta = beta;
  67685. _this.radius = radius;
  67686. _this.target = target;
  67687. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67688. _this.follow();
  67689. return _this;
  67690. }
  67691. ArcFollowCamera.prototype.follow = function () {
  67692. if (!this.target) {
  67693. return;
  67694. }
  67695. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67696. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67697. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67698. var targetPosition = this.target.getAbsolutePosition();
  67699. this.position = targetPosition.add(this._cartesianCoordinates);
  67700. this.setTarget(targetPosition);
  67701. };
  67702. ArcFollowCamera.prototype._checkInputs = function () {
  67703. _super.prototype._checkInputs.call(this);
  67704. this.follow();
  67705. };
  67706. ArcFollowCamera.prototype.getClassName = function () {
  67707. return "ArcFollowCamera";
  67708. };
  67709. return ArcFollowCamera;
  67710. }(BABYLON.TargetCamera));
  67711. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67712. })(BABYLON || (BABYLON = {}));
  67713. //# sourceMappingURL=babylon.followCamera.js.map
  67714. "use strict";
  67715. var BABYLON;
  67716. (function (BABYLON) {
  67717. // We're mainly based on the logic defined into the FreeCamera code
  67718. var UniversalCamera = /** @class */ (function (_super) {
  67719. __extends(UniversalCamera, _super);
  67720. //-- end properties for backward compatibility for inputs
  67721. function UniversalCamera(name, position, scene) {
  67722. var _this = _super.call(this, name, position, scene) || this;
  67723. _this.inputs.addGamepad();
  67724. return _this;
  67725. }
  67726. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67727. //-- Begin properties for backward compatibility for inputs
  67728. get: function () {
  67729. var gamepad = this.inputs.attached["gamepad"];
  67730. if (gamepad)
  67731. return gamepad.gamepadAngularSensibility;
  67732. return 0;
  67733. },
  67734. set: function (value) {
  67735. var gamepad = this.inputs.attached["gamepad"];
  67736. if (gamepad)
  67737. gamepad.gamepadAngularSensibility = value;
  67738. },
  67739. enumerable: true,
  67740. configurable: true
  67741. });
  67742. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67743. get: function () {
  67744. var gamepad = this.inputs.attached["gamepad"];
  67745. if (gamepad)
  67746. return gamepad.gamepadMoveSensibility;
  67747. return 0;
  67748. },
  67749. set: function (value) {
  67750. var gamepad = this.inputs.attached["gamepad"];
  67751. if (gamepad)
  67752. gamepad.gamepadMoveSensibility = value;
  67753. },
  67754. enumerable: true,
  67755. configurable: true
  67756. });
  67757. UniversalCamera.prototype.getClassName = function () {
  67758. return "UniversalCamera";
  67759. };
  67760. return UniversalCamera;
  67761. }(BABYLON.TouchCamera));
  67762. BABYLON.UniversalCamera = UniversalCamera;
  67763. })(BABYLON || (BABYLON = {}));
  67764. //# sourceMappingURL=babylon.universalCamera.js.map
  67765. "use strict";
  67766. var BABYLON;
  67767. (function (BABYLON) {
  67768. // We're mainly based on the logic defined into the FreeCamera code
  67769. var GamepadCamera = /** @class */ (function (_super) {
  67770. __extends(GamepadCamera, _super);
  67771. //-- end properties for backward compatibility for inputs
  67772. function GamepadCamera(name, position, scene) {
  67773. return _super.call(this, name, position, scene) || this;
  67774. }
  67775. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67776. //-- Begin properties for backward compatibility for inputs
  67777. get: function () {
  67778. var gamepad = this.inputs.attached["gamepad"];
  67779. if (gamepad)
  67780. return gamepad.gamepadAngularSensibility;
  67781. return 0;
  67782. },
  67783. set: function (value) {
  67784. var gamepad = this.inputs.attached["gamepad"];
  67785. if (gamepad)
  67786. gamepad.gamepadAngularSensibility = value;
  67787. },
  67788. enumerable: true,
  67789. configurable: true
  67790. });
  67791. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67792. get: function () {
  67793. var gamepad = this.inputs.attached["gamepad"];
  67794. if (gamepad)
  67795. return gamepad.gamepadMoveSensibility;
  67796. return 0;
  67797. },
  67798. set: function (value) {
  67799. var gamepad = this.inputs.attached["gamepad"];
  67800. if (gamepad)
  67801. gamepad.gamepadMoveSensibility = value;
  67802. },
  67803. enumerable: true,
  67804. configurable: true
  67805. });
  67806. GamepadCamera.prototype.getClassName = function () {
  67807. return "GamepadCamera";
  67808. };
  67809. return GamepadCamera;
  67810. }(BABYLON.UniversalCamera));
  67811. BABYLON.GamepadCamera = GamepadCamera;
  67812. })(BABYLON || (BABYLON = {}));
  67813. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67814. "use strict";
  67815. var BABYLON;
  67816. (function (BABYLON) {
  67817. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67818. function PostProcessRenderPipelineManager() {
  67819. this._renderPipelines = {};
  67820. }
  67821. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67822. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67823. };
  67824. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67825. if (unique === void 0) { unique = false; }
  67826. var renderPipeline = this._renderPipelines[renderPipelineName];
  67827. if (!renderPipeline) {
  67828. return;
  67829. }
  67830. renderPipeline._attachCameras(cameras, unique);
  67831. };
  67832. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67833. var renderPipeline = this._renderPipelines[renderPipelineName];
  67834. if (!renderPipeline) {
  67835. return;
  67836. }
  67837. renderPipeline._detachCameras(cameras);
  67838. };
  67839. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67840. var renderPipeline = this._renderPipelines[renderPipelineName];
  67841. if (!renderPipeline) {
  67842. return;
  67843. }
  67844. renderPipeline._enableEffect(renderEffectName, cameras);
  67845. };
  67846. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67847. var renderPipeline = this._renderPipelines[renderPipelineName];
  67848. if (!renderPipeline) {
  67849. return;
  67850. }
  67851. renderPipeline._disableEffect(renderEffectName, cameras);
  67852. };
  67853. PostProcessRenderPipelineManager.prototype.update = function () {
  67854. for (var renderPipelineName in this._renderPipelines) {
  67855. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67856. var pipeline = this._renderPipelines[renderPipelineName];
  67857. if (!pipeline.isSupported) {
  67858. pipeline.dispose();
  67859. delete this._renderPipelines[renderPipelineName];
  67860. }
  67861. else {
  67862. pipeline._update();
  67863. }
  67864. }
  67865. }
  67866. };
  67867. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67868. for (var renderPipelineName in this._renderPipelines) {
  67869. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67870. var pipeline = this._renderPipelines[renderPipelineName];
  67871. pipeline._rebuild();
  67872. }
  67873. }
  67874. };
  67875. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67876. for (var renderPipelineName in this._renderPipelines) {
  67877. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67878. var pipeline = this._renderPipelines[renderPipelineName];
  67879. pipeline.dispose();
  67880. }
  67881. }
  67882. };
  67883. return PostProcessRenderPipelineManager;
  67884. }());
  67885. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67886. })(BABYLON || (BABYLON = {}));
  67887. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67888. "use strict";
  67889. var BABYLON;
  67890. (function (BABYLON) {
  67891. /**
  67892. * This represents a set of one or more post processes in Babylon.
  67893. * A post process can be used to apply a shader to a texture after it is rendered.
  67894. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67895. */
  67896. var PostProcessRenderEffect = /** @class */ (function () {
  67897. /**
  67898. * Instantiates a post process render effect.
  67899. * A post process can be used to apply a shader to a texture after it is rendered.
  67900. * @param engine The engine the effect is tied to
  67901. * @param name The name of the effect
  67902. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67903. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67904. */
  67905. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67906. this._name = name;
  67907. this._singleInstance = singleInstance || true;
  67908. this._getPostProcesses = getPostProcesses;
  67909. this._cameras = {};
  67910. this._indicesForCamera = {};
  67911. this._postProcesses = {};
  67912. }
  67913. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67914. /**
  67915. * Checks if all the post processes in the effect are supported.
  67916. */
  67917. get: function () {
  67918. for (var index in this._postProcesses) {
  67919. for (var ppIndex in this._postProcesses[index]) {
  67920. if (!this._postProcesses[index][ppIndex].isSupported) {
  67921. return false;
  67922. }
  67923. }
  67924. }
  67925. return true;
  67926. },
  67927. enumerable: true,
  67928. configurable: true
  67929. });
  67930. /**
  67931. * Updates the current state of the effect
  67932. */
  67933. PostProcessRenderEffect.prototype._update = function () {
  67934. };
  67935. /**
  67936. * Attaches the effect on cameras
  67937. * @param cameras The camera to attach to.
  67938. */
  67939. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67940. var _this = this;
  67941. var cameraKey;
  67942. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67943. if (!cams) {
  67944. return;
  67945. }
  67946. for (var i = 0; i < cams.length; i++) {
  67947. var camera = cams[i];
  67948. var cameraName = camera.name;
  67949. if (this._singleInstance) {
  67950. cameraKey = 0;
  67951. }
  67952. else {
  67953. cameraKey = cameraName;
  67954. }
  67955. if (!this._postProcesses[cameraKey]) {
  67956. var postProcess = this._getPostProcesses();
  67957. if (postProcess) {
  67958. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67959. }
  67960. }
  67961. if (!this._indicesForCamera[cameraName]) {
  67962. this._indicesForCamera[cameraName] = [];
  67963. }
  67964. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67965. var index = camera.attachPostProcess(postProcess);
  67966. _this._indicesForCamera[cameraName].push(index);
  67967. });
  67968. if (!this._cameras[cameraName]) {
  67969. this._cameras[cameraName] = camera;
  67970. }
  67971. }
  67972. };
  67973. /**
  67974. * Detatches the effect on cameras
  67975. * @param cameras The camera to detatch from.
  67976. */
  67977. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67978. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67979. if (!cams) {
  67980. return;
  67981. }
  67982. for (var i = 0; i < cams.length; i++) {
  67983. var camera = cams[i];
  67984. var cameraName = camera.name;
  67985. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67986. camera.detachPostProcess(postProcess);
  67987. });
  67988. if (this._cameras[cameraName]) {
  67989. //this._indicesForCamera.splice(index, 1);
  67990. this._cameras[cameraName] = null;
  67991. }
  67992. }
  67993. };
  67994. /**
  67995. * Enables the effect on given cameras
  67996. * @param cameras The camera to enable.
  67997. */
  67998. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67999. var _this = this;
  68000. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68001. if (!cams) {
  68002. return;
  68003. }
  68004. for (var i = 0; i < cams.length; i++) {
  68005. var camera = cams[i];
  68006. var cameraName = camera.name;
  68007. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  68008. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  68009. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68010. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  68011. });
  68012. }
  68013. }
  68014. }
  68015. };
  68016. /**
  68017. * Disables the effect on the given cameras
  68018. * @param cameras The camera to disable.
  68019. */
  68020. PostProcessRenderEffect.prototype._disable = function (cameras) {
  68021. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68022. if (!cams) {
  68023. return;
  68024. }
  68025. for (var i = 0; i < cams.length; i++) {
  68026. var camera = cams[i];
  68027. var cameraName = camera.name;
  68028. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68029. camera.detachPostProcess(postProcess);
  68030. });
  68031. }
  68032. };
  68033. /**
  68034. * Gets a list of the post processes contained in the effect.
  68035. * @param camera The camera to get the post processes on.
  68036. * @returns The list of the post processes in the effect.
  68037. */
  68038. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  68039. if (this._singleInstance) {
  68040. return this._postProcesses[0];
  68041. }
  68042. else {
  68043. if (!camera) {
  68044. return null;
  68045. }
  68046. return this._postProcesses[camera.name];
  68047. }
  68048. };
  68049. return PostProcessRenderEffect;
  68050. }());
  68051. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  68052. })(BABYLON || (BABYLON = {}));
  68053. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  68054. "use strict";
  68055. var BABYLON;
  68056. (function (BABYLON) {
  68057. var PostProcessRenderPipeline = /** @class */ (function () {
  68058. function PostProcessRenderPipeline(engine, name) {
  68059. this.engine = engine;
  68060. this._name = name;
  68061. this._renderEffects = {};
  68062. this._renderEffectsForIsolatedPass = new Array();
  68063. this._cameras = [];
  68064. }
  68065. PostProcessRenderPipeline.prototype.getClassName = function () {
  68066. return "PostProcessRenderPipeline";
  68067. };
  68068. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  68069. get: function () {
  68070. for (var renderEffectName in this._renderEffects) {
  68071. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68072. if (!this._renderEffects[renderEffectName].isSupported) {
  68073. return false;
  68074. }
  68075. }
  68076. }
  68077. return true;
  68078. },
  68079. enumerable: true,
  68080. configurable: true
  68081. });
  68082. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  68083. this._renderEffects[renderEffect._name] = renderEffect;
  68084. };
  68085. // private
  68086. PostProcessRenderPipeline.prototype._rebuild = function () {
  68087. };
  68088. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  68089. var renderEffects = this._renderEffects[renderEffectName];
  68090. if (!renderEffects) {
  68091. return;
  68092. }
  68093. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68094. };
  68095. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  68096. var renderEffects = this._renderEffects[renderEffectName];
  68097. if (!renderEffects) {
  68098. return;
  68099. }
  68100. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68101. };
  68102. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  68103. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68104. if (!cams) {
  68105. return;
  68106. }
  68107. var indicesToDelete = [];
  68108. var i;
  68109. for (i = 0; i < cams.length; i++) {
  68110. var camera = cams[i];
  68111. var cameraName = camera.name;
  68112. if (this._cameras.indexOf(camera) === -1) {
  68113. this._cameras[cameraName] = camera;
  68114. }
  68115. else if (unique) {
  68116. indicesToDelete.push(i);
  68117. }
  68118. }
  68119. for (i = 0; i < indicesToDelete.length; i++) {
  68120. cameras.splice(indicesToDelete[i], 1);
  68121. }
  68122. for (var renderEffectName in this._renderEffects) {
  68123. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68124. this._renderEffects[renderEffectName]._attachCameras(cams);
  68125. }
  68126. }
  68127. };
  68128. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  68129. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68130. if (!cams) {
  68131. return;
  68132. }
  68133. for (var renderEffectName in this._renderEffects) {
  68134. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68135. this._renderEffects[renderEffectName]._detachCameras(cams);
  68136. }
  68137. }
  68138. for (var i = 0; i < cams.length; i++) {
  68139. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  68140. }
  68141. };
  68142. PostProcessRenderPipeline.prototype._update = function () {
  68143. for (var renderEffectName in this._renderEffects) {
  68144. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68145. this._renderEffects[renderEffectName]._update();
  68146. }
  68147. }
  68148. for (var i = 0; i < this._cameras.length; i++) {
  68149. var cameraName = this._cameras[i].name;
  68150. if (this._renderEffectsForIsolatedPass[cameraName]) {
  68151. this._renderEffectsForIsolatedPass[cameraName]._update();
  68152. }
  68153. }
  68154. };
  68155. PostProcessRenderPipeline.prototype._reset = function () {
  68156. this._renderEffects = {};
  68157. this._renderEffectsForIsolatedPass = new Array();
  68158. };
  68159. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  68160. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  68161. var effectKeys = Object.keys(this._renderEffects);
  68162. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  68163. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  68164. if (postProcesses) {
  68165. postProcesses[0].samples = 4;
  68166. return true;
  68167. }
  68168. }
  68169. return false;
  68170. };
  68171. PostProcessRenderPipeline.prototype.dispose = function () {
  68172. // Must be implemented by children
  68173. };
  68174. __decorate([
  68175. BABYLON.serialize()
  68176. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  68177. return PostProcessRenderPipeline;
  68178. }());
  68179. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  68180. })(BABYLON || (BABYLON = {}));
  68181. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  68182. "use strict";
  68183. var BABYLON;
  68184. (function (BABYLON) {
  68185. /**
  68186. * This represents a depth renderer in Babylon.
  68187. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  68188. */
  68189. var DepthRenderer = /** @class */ (function () {
  68190. /**
  68191. * Instantiates a depth renderer
  68192. * @param scene The scene the renderer belongs to
  68193. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  68194. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  68195. */
  68196. function DepthRenderer(scene, type, camera) {
  68197. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68198. if (camera === void 0) { camera = null; }
  68199. var _this = this;
  68200. this._scene = scene;
  68201. this._camera = camera;
  68202. var engine = scene.getEngine();
  68203. // Render target
  68204. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  68205. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68206. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68207. this._depthMap.refreshRate = 1;
  68208. this._depthMap.renderParticles = false;
  68209. this._depthMap.renderList = null;
  68210. // Camera to get depth map from to support multiple concurrent cameras
  68211. this._depthMap.activeCamera = this._camera;
  68212. this._depthMap.ignoreCameraViewport = true;
  68213. this._depthMap.useCameraPostProcesses = false;
  68214. // set default depth value to 1.0 (far away)
  68215. this._depthMap.onClearObservable.add(function (engine) {
  68216. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  68217. });
  68218. // Custom render function
  68219. var renderSubMesh = function (subMesh) {
  68220. var mesh = subMesh.getRenderingMesh();
  68221. var scene = _this._scene;
  68222. var engine = scene.getEngine();
  68223. var material = subMesh.getMaterial();
  68224. if (!material) {
  68225. return;
  68226. }
  68227. // Culling and reverse (right handed system)
  68228. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68229. // Managing instances
  68230. var batch = mesh._getInstancesRenderList(subMesh._id);
  68231. if (batch.mustReturn) {
  68232. return;
  68233. }
  68234. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68235. var camera = _this._camera || scene.activeCamera;
  68236. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  68237. engine.enableEffect(_this._effect);
  68238. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68239. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68240. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  68241. // Alpha test
  68242. if (material && material.needAlphaTesting()) {
  68243. var alphaTexture = material.getAlphaTestTexture();
  68244. if (alphaTexture) {
  68245. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68246. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68247. }
  68248. }
  68249. // Bones
  68250. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68251. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68252. }
  68253. // Draw
  68254. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68255. }
  68256. };
  68257. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68258. var index;
  68259. if (depthOnlySubMeshes.length) {
  68260. engine.setColorWrite(false);
  68261. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68262. renderSubMesh(depthOnlySubMeshes.data[index]);
  68263. }
  68264. engine.setColorWrite(true);
  68265. }
  68266. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68267. renderSubMesh(opaqueSubMeshes.data[index]);
  68268. }
  68269. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68270. renderSubMesh(alphaTestSubMeshes.data[index]);
  68271. }
  68272. };
  68273. }
  68274. /**
  68275. * Creates the depth rendering effect and checks if the effect is ready.
  68276. * @param subMesh The submesh to be used to render the depth map of
  68277. * @param useInstances If multiple world instances should be used
  68278. * @returns if the depth renderer is ready to render the depth map
  68279. */
  68280. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  68281. var material = subMesh.getMaterial();
  68282. if (material.disableDepthWrite) {
  68283. return false;
  68284. }
  68285. var defines = [];
  68286. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68287. var mesh = subMesh.getMesh();
  68288. // Alpha test
  68289. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  68290. defines.push("#define ALPHATEST");
  68291. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68292. attribs.push(BABYLON.VertexBuffer.UVKind);
  68293. defines.push("#define UV1");
  68294. }
  68295. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68296. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68297. defines.push("#define UV2");
  68298. }
  68299. }
  68300. // Bones
  68301. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68302. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68303. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68304. if (mesh.numBoneInfluencers > 4) {
  68305. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68306. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68307. }
  68308. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68309. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68310. }
  68311. else {
  68312. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68313. }
  68314. // Instances
  68315. if (useInstances) {
  68316. defines.push("#define INSTANCES");
  68317. attribs.push("world0");
  68318. attribs.push("world1");
  68319. attribs.push("world2");
  68320. attribs.push("world3");
  68321. }
  68322. // Get correct effect
  68323. var join = defines.join("\n");
  68324. if (this._cachedDefines !== join) {
  68325. this._cachedDefines = join;
  68326. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68327. }
  68328. return this._effect.isReady();
  68329. };
  68330. /**
  68331. * Gets the texture which the depth map will be written to.
  68332. * @returns The depth map texture
  68333. */
  68334. DepthRenderer.prototype.getDepthMap = function () {
  68335. return this._depthMap;
  68336. };
  68337. /**
  68338. * Disposes of the depth renderer.
  68339. */
  68340. DepthRenderer.prototype.dispose = function () {
  68341. this._depthMap.dispose();
  68342. };
  68343. return DepthRenderer;
  68344. }());
  68345. BABYLON.DepthRenderer = DepthRenderer;
  68346. })(BABYLON || (BABYLON = {}));
  68347. //# sourceMappingURL=babylon.depthRenderer.js.map
  68348. "use strict";
  68349. var BABYLON;
  68350. (function (BABYLON) {
  68351. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68352. __extends(SSAORenderingPipeline, _super);
  68353. /**
  68354. * @constructor
  68355. * @param {string} name - The rendering pipeline name
  68356. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68357. * @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 }
  68358. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68359. */
  68360. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68361. var _this = _super.call(this, scene.getEngine(), name) || this;
  68362. // Members
  68363. /**
  68364. * The PassPostProcess id in the pipeline that contains the original scene color
  68365. * @type {string}
  68366. */
  68367. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68368. /**
  68369. * The SSAO PostProcess id in the pipeline
  68370. * @type {string}
  68371. */
  68372. _this.SSAORenderEffect = "SSAORenderEffect";
  68373. /**
  68374. * The horizontal blur PostProcess id in the pipeline
  68375. * @type {string}
  68376. */
  68377. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68378. /**
  68379. * The vertical blur PostProcess id in the pipeline
  68380. * @type {string}
  68381. */
  68382. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68383. /**
  68384. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68385. * @type {string}
  68386. */
  68387. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68388. /**
  68389. * The output strength of the SSAO post-process. Default value is 1.0.
  68390. * @type {number}
  68391. */
  68392. _this.totalStrength = 1.0;
  68393. /**
  68394. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68395. * @type {number}
  68396. */
  68397. _this.radius = 0.0001;
  68398. /**
  68399. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68400. * Must not be equal to fallOff and superior to fallOff.
  68401. * Default value is 0.975
  68402. * @type {number}
  68403. */
  68404. _this.area = 0.0075;
  68405. /**
  68406. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68407. * Must not be equal to area and inferior to area.
  68408. * Default value is 0.0
  68409. * @type {number}
  68410. */
  68411. _this.fallOff = 0.000001;
  68412. /**
  68413. * The base color of the SSAO post-process
  68414. * The final result is "base + ssao" between [0, 1]
  68415. * @type {number}
  68416. */
  68417. _this.base = 0.5;
  68418. _this._firstUpdate = true;
  68419. _this._scene = scene;
  68420. // Set up assets
  68421. _this._createRandomTexture();
  68422. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68423. var ssaoRatio = ratio.ssaoRatio || ratio;
  68424. var combineRatio = ratio.combineRatio || ratio;
  68425. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68426. _this._createSSAOPostProcess(ssaoRatio);
  68427. _this._createBlurPostProcess(ssaoRatio);
  68428. _this._createSSAOCombinePostProcess(combineRatio);
  68429. // Set up pipeline
  68430. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68431. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68432. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68433. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68434. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68435. // Finish
  68436. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68437. if (cameras)
  68438. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68439. return _this;
  68440. }
  68441. // Public Methods
  68442. /**
  68443. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68444. */
  68445. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68446. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68447. for (var i = 0; i < this._scene.cameras.length; i++) {
  68448. var camera = this._scene.cameras[i];
  68449. this._originalColorPostProcess.dispose(camera);
  68450. this._ssaoPostProcess.dispose(camera);
  68451. this._blurHPostProcess.dispose(camera);
  68452. this._blurVPostProcess.dispose(camera);
  68453. this._ssaoCombinePostProcess.dispose(camera);
  68454. }
  68455. this._randomTexture.dispose();
  68456. if (disableDepthRender)
  68457. this._scene.disableDepthRenderer();
  68458. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68459. _super.prototype.dispose.call(this);
  68460. };
  68461. // Private Methods
  68462. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68463. var _this = this;
  68464. var size = 16;
  68465. 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);
  68466. 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);
  68467. this._blurHPostProcess.onActivateObservable.add(function () {
  68468. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68469. _this._blurHPostProcess.kernel = size * dw;
  68470. });
  68471. this._blurVPostProcess.onActivateObservable.add(function () {
  68472. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68473. _this._blurVPostProcess.kernel = size * dw;
  68474. });
  68475. };
  68476. SSAORenderingPipeline.prototype._rebuild = function () {
  68477. this._firstUpdate = true;
  68478. _super.prototype._rebuild.call(this);
  68479. };
  68480. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68481. var _this = this;
  68482. var numSamples = 16;
  68483. var sampleSphere = [
  68484. 0.5381, 0.1856, -0.4319,
  68485. 0.1379, 0.2486, 0.4430,
  68486. 0.3371, 0.5679, -0.0057,
  68487. -0.6999, -0.0451, -0.0019,
  68488. 0.0689, -0.1598, -0.8547,
  68489. 0.0560, 0.0069, -0.1843,
  68490. -0.0146, 0.1402, 0.0762,
  68491. 0.0100, -0.1924, -0.0344,
  68492. -0.3577, -0.5301, -0.4358,
  68493. -0.3169, 0.1063, 0.0158,
  68494. 0.0103, -0.5869, 0.0046,
  68495. -0.0897, -0.4940, 0.3287,
  68496. 0.7119, -0.0154, -0.0918,
  68497. -0.0533, 0.0596, -0.5411,
  68498. 0.0352, -0.0631, 0.5460,
  68499. -0.4776, 0.2847, -0.0271
  68500. ];
  68501. var samplesFactor = 1.0 / numSamples;
  68502. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68503. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68504. "area", "fallOff", "base", "range", "viewport"
  68505. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68506. this._ssaoPostProcess.onApply = function (effect) {
  68507. if (_this._firstUpdate) {
  68508. effect.setArray3("sampleSphere", sampleSphere);
  68509. effect.setFloat("samplesFactor", samplesFactor);
  68510. effect.setFloat("randTextureTiles", 4.0);
  68511. }
  68512. effect.setFloat("totalStrength", _this.totalStrength);
  68513. effect.setFloat("radius", _this.radius);
  68514. effect.setFloat("area", _this.area);
  68515. effect.setFloat("fallOff", _this.fallOff);
  68516. effect.setFloat("base", _this.base);
  68517. effect.setTexture("textureSampler", _this._depthTexture);
  68518. effect.setTexture("randomSampler", _this._randomTexture);
  68519. };
  68520. };
  68521. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68522. var _this = this;
  68523. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68524. this._ssaoCombinePostProcess.onApply = function (effect) {
  68525. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68526. };
  68527. };
  68528. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68529. var size = 512;
  68530. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68531. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68532. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68533. var context = this._randomTexture.getContext();
  68534. var rand = function (min, max) {
  68535. return Math.random() * (max - min) + min;
  68536. };
  68537. var randVector = BABYLON.Vector3.Zero();
  68538. for (var x = 0; x < size; x++) {
  68539. for (var y = 0; y < size; y++) {
  68540. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68541. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68542. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68543. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68544. context.fillRect(x, y, 1, 1);
  68545. }
  68546. }
  68547. this._randomTexture.update(false);
  68548. };
  68549. __decorate([
  68550. BABYLON.serialize()
  68551. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68552. __decorate([
  68553. BABYLON.serialize()
  68554. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68555. __decorate([
  68556. BABYLON.serialize()
  68557. ], SSAORenderingPipeline.prototype, "area", void 0);
  68558. __decorate([
  68559. BABYLON.serialize()
  68560. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68561. __decorate([
  68562. BABYLON.serialize()
  68563. ], SSAORenderingPipeline.prototype, "base", void 0);
  68564. return SSAORenderingPipeline;
  68565. }(BABYLON.PostProcessRenderPipeline));
  68566. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68567. })(BABYLON || (BABYLON = {}));
  68568. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68569. "use strict";
  68570. var BABYLON;
  68571. (function (BABYLON) {
  68572. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68573. __extends(SSAO2RenderingPipeline, _super);
  68574. /**
  68575. * @constructor
  68576. * @param {string} name - The rendering pipeline name
  68577. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68578. * @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 }
  68579. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68580. */
  68581. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68582. var _this = _super.call(this, scene.getEngine(), name) || this;
  68583. // Members
  68584. /**
  68585. * The PassPostProcess id in the pipeline that contains the original scene color
  68586. * @type {string}
  68587. */
  68588. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68589. /**
  68590. * The SSAO PostProcess id in the pipeline
  68591. * @type {string}
  68592. */
  68593. _this.SSAORenderEffect = "SSAORenderEffect";
  68594. /**
  68595. * The horizontal blur PostProcess id in the pipeline
  68596. * @type {string}
  68597. */
  68598. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68599. /**
  68600. * The vertical blur PostProcess id in the pipeline
  68601. * @type {string}
  68602. */
  68603. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68604. /**
  68605. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68606. * @type {string}
  68607. */
  68608. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68609. /**
  68610. * The output strength of the SSAO post-process. Default value is 1.0.
  68611. * @type {number}
  68612. */
  68613. _this.totalStrength = 1.0;
  68614. /**
  68615. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68616. * @type {number}
  68617. */
  68618. _this.maxZ = 100.0;
  68619. /**
  68620. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68621. * @type {number}
  68622. */
  68623. _this.minZAspect = 0.2;
  68624. /**
  68625. * Number of samples used for the SSAO calculations. Default value is 8
  68626. * @type {number}
  68627. */
  68628. _this._samples = 8;
  68629. /**
  68630. * Are we using bilateral blur ?
  68631. * @type {boolean}
  68632. */
  68633. _this._expensiveBlur = true;
  68634. /**
  68635. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68636. * @type {number}
  68637. */
  68638. _this.radius = 2.0;
  68639. /**
  68640. * The base color of the SSAO post-process
  68641. * The final result is "base + ssao" between [0, 1]
  68642. * @type {number}
  68643. */
  68644. _this.base = 0.1;
  68645. _this._firstUpdate = true;
  68646. _this._scene = scene;
  68647. if (!_this.isSupported) {
  68648. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68649. return _this;
  68650. }
  68651. var ssaoRatio = ratio.ssaoRatio || ratio;
  68652. var blurRatio = ratio.blurRatio || ratio;
  68653. // Set up assets
  68654. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68655. _this._createRandomTexture();
  68656. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68657. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68658. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68659. _this._createSSAOPostProcess(1.0);
  68660. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68661. _this._createSSAOCombinePostProcess(blurRatio);
  68662. // Set up pipeline
  68663. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68664. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68665. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68666. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68667. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68668. // Finish
  68669. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68670. if (cameras)
  68671. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68672. return _this;
  68673. }
  68674. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68675. get: function () {
  68676. return this._samples;
  68677. },
  68678. set: function (n) {
  68679. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68680. this._samples = n;
  68681. this._sampleSphere = this._generateHemisphere();
  68682. this._firstUpdate = true;
  68683. },
  68684. enumerable: true,
  68685. configurable: true
  68686. });
  68687. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68688. get: function () {
  68689. return this._expensiveBlur;
  68690. },
  68691. set: function (b) {
  68692. 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"]);
  68693. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68694. this._expensiveBlur = b;
  68695. this._firstUpdate = true;
  68696. },
  68697. enumerable: true,
  68698. configurable: true
  68699. });
  68700. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68701. /**
  68702. * Support test.
  68703. * @type {boolean}
  68704. */
  68705. get: function () {
  68706. var engine = BABYLON.Engine.LastCreatedEngine;
  68707. if (!engine) {
  68708. return false;
  68709. }
  68710. return engine.getCaps().drawBuffersExtension;
  68711. },
  68712. enumerable: true,
  68713. configurable: true
  68714. });
  68715. // Public Methods
  68716. /**
  68717. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68718. */
  68719. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68720. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68721. for (var i = 0; i < this._scene.cameras.length; i++) {
  68722. var camera = this._scene.cameras[i];
  68723. this._originalColorPostProcess.dispose(camera);
  68724. this._ssaoPostProcess.dispose(camera);
  68725. this._blurHPostProcess.dispose(camera);
  68726. this._blurVPostProcess.dispose(camera);
  68727. this._ssaoCombinePostProcess.dispose(camera);
  68728. }
  68729. this._randomTexture.dispose();
  68730. if (disableGeometryBufferRenderer)
  68731. this._scene.disableGeometryBufferRenderer();
  68732. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68733. _super.prototype.dispose.call(this);
  68734. };
  68735. // Private Methods
  68736. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68737. var _this = this;
  68738. this._samplerOffsets = [];
  68739. var expensive = this.expensiveBlur;
  68740. for (var i = -8; i < 8; i++) {
  68741. this._samplerOffsets.push(i * 2 + 0.5);
  68742. }
  68743. 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");
  68744. this._blurHPostProcess.onApply = function (effect) {
  68745. if (!_this._scene.activeCamera) {
  68746. return;
  68747. }
  68748. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68749. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68750. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68751. effect.setFloat("radius", _this.radius);
  68752. effect.setTexture("depthSampler", _this._depthTexture);
  68753. if (_this._firstUpdate) {
  68754. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68755. }
  68756. };
  68757. 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");
  68758. this._blurVPostProcess.onApply = function (effect) {
  68759. if (!_this._scene.activeCamera) {
  68760. return;
  68761. }
  68762. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68763. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68764. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68765. effect.setFloat("radius", _this.radius);
  68766. effect.setTexture("depthSampler", _this._depthTexture);
  68767. if (_this._firstUpdate) {
  68768. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68769. _this._firstUpdate = false;
  68770. }
  68771. };
  68772. };
  68773. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68774. this._firstUpdate = true;
  68775. _super.prototype._rebuild.call(this);
  68776. };
  68777. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68778. var numSamples = this.samples;
  68779. var result = [];
  68780. var vector, scale;
  68781. var rand = function (min, max) {
  68782. return Math.random() * (max - min) + min;
  68783. };
  68784. var i = 0;
  68785. while (i < numSamples) {
  68786. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68787. vector.normalize();
  68788. scale = i / numSamples;
  68789. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68790. vector.scaleInPlace(scale);
  68791. result.push(vector.x, vector.y, vector.z);
  68792. i++;
  68793. }
  68794. return result;
  68795. };
  68796. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68797. var _this = this;
  68798. var numSamples = this.samples;
  68799. this._sampleSphere = this._generateHemisphere();
  68800. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68801. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68802. "base", "range", "projection", "near", "far", "texelSize",
  68803. "xViewport", "yViewport", "maxZ", "minZAspect"
  68804. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68805. this._ssaoPostProcess.onApply = function (effect) {
  68806. if (_this._firstUpdate) {
  68807. effect.setArray3("sampleSphere", _this._sampleSphere);
  68808. effect.setFloat("randTextureTiles", 4.0);
  68809. }
  68810. if (!_this._scene.activeCamera) {
  68811. return;
  68812. }
  68813. effect.setFloat("samplesFactor", 1 / _this.samples);
  68814. effect.setFloat("totalStrength", _this.totalStrength);
  68815. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68816. effect.setFloat("radius", _this.radius);
  68817. effect.setFloat("maxZ", _this.maxZ);
  68818. effect.setFloat("minZAspect", _this.minZAspect);
  68819. effect.setFloat("base", _this.base);
  68820. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68821. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68822. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68823. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68824. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68825. effect.setTexture("textureSampler", _this._depthTexture);
  68826. effect.setTexture("normalSampler", _this._normalTexture);
  68827. effect.setTexture("randomSampler", _this._randomTexture);
  68828. };
  68829. };
  68830. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68831. var _this = this;
  68832. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68833. this._ssaoCombinePostProcess.onApply = function (effect) {
  68834. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68835. };
  68836. };
  68837. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68838. var size = 512;
  68839. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68840. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68841. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68842. var context = this._randomTexture.getContext();
  68843. var rand = function (min, max) {
  68844. return Math.random() * (max - min) + min;
  68845. };
  68846. var randVector = BABYLON.Vector3.Zero();
  68847. for (var x = 0; x < size; x++) {
  68848. for (var y = 0; y < size; y++) {
  68849. randVector.x = rand(0.0, 1.0);
  68850. randVector.y = rand(0.0, 1.0);
  68851. randVector.z = 0.0;
  68852. randVector.normalize();
  68853. randVector.scaleInPlace(255);
  68854. randVector.x = Math.floor(randVector.x);
  68855. randVector.y = Math.floor(randVector.y);
  68856. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68857. context.fillRect(x, y, 1, 1);
  68858. }
  68859. }
  68860. this._randomTexture.update(false);
  68861. };
  68862. __decorate([
  68863. BABYLON.serialize()
  68864. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68865. __decorate([
  68866. BABYLON.serialize()
  68867. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68868. __decorate([
  68869. BABYLON.serialize()
  68870. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68871. __decorate([
  68872. BABYLON.serialize("samples")
  68873. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68874. __decorate([
  68875. BABYLON.serialize("expensiveBlur")
  68876. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68877. __decorate([
  68878. BABYLON.serialize()
  68879. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68880. __decorate([
  68881. BABYLON.serialize()
  68882. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68883. return SSAO2RenderingPipeline;
  68884. }(BABYLON.PostProcessRenderPipeline));
  68885. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68886. })(BABYLON || (BABYLON = {}));
  68887. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68888. "use strict";
  68889. // BABYLON.JS Chromatic Aberration GLSL Shader
  68890. // Author: Olivier Guyot
  68891. // Separates very slightly R, G and B colors on the edges of the screen
  68892. // Inspired by Francois Tarlier & Martins Upitis
  68893. var BABYLON;
  68894. (function (BABYLON) {
  68895. var LensRenderingPipeline = /** @class */ (function (_super) {
  68896. __extends(LensRenderingPipeline, _super);
  68897. /**
  68898. * @constructor
  68899. *
  68900. * Effect parameters are as follow:
  68901. * {
  68902. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68903. * edge_blur: number; // from 0 to x (1 for realism)
  68904. * distortion: number; // from 0 to x (1 for realism)
  68905. * grain_amount: number; // from 0 to 1
  68906. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68907. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68908. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68909. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68910. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68911. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68912. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68913. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68914. * }
  68915. * Note: if an effect parameter is unset, effect is disabled
  68916. *
  68917. * @param {string} name - The rendering pipeline name
  68918. * @param {object} parameters - An object containing all parameters (see above)
  68919. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68920. * @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)
  68921. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68922. */
  68923. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68924. if (ratio === void 0) { ratio = 1.0; }
  68925. var _this = _super.call(this, scene.getEngine(), name) || this;
  68926. // Lens effects can be of the following:
  68927. // - chromatic aberration (slight shift of RGB colors)
  68928. // - blur on the edge of the lens
  68929. // - lens distortion
  68930. // - depth-of-field blur & highlights enhancing
  68931. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68932. // - grain effect (noise or custom texture)
  68933. // Two additional texture samplers are needed:
  68934. // - depth map (for depth-of-field)
  68935. // - grain texture
  68936. /**
  68937. * The chromatic aberration PostProcess id in the pipeline
  68938. * @type {string}
  68939. */
  68940. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68941. /**
  68942. * The highlights enhancing PostProcess id in the pipeline
  68943. * @type {string}
  68944. */
  68945. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68946. /**
  68947. * The depth-of-field PostProcess id in the pipeline
  68948. * @type {string}
  68949. */
  68950. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68951. _this._scene = scene;
  68952. // Fetch texture samplers
  68953. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68954. if (parameters.grain_texture) {
  68955. _this._grainTexture = parameters.grain_texture;
  68956. }
  68957. else {
  68958. _this._createGrainTexture();
  68959. }
  68960. // save parameters
  68961. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68962. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68963. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68964. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68965. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68966. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68967. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68968. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68969. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68970. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68971. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68972. // Create effects
  68973. _this._createChromaticAberrationPostProcess(ratio);
  68974. _this._createHighlightsPostProcess(ratio);
  68975. _this._createDepthOfFieldPostProcess(ratio / 4);
  68976. // Set up pipeline
  68977. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68978. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68979. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68980. if (_this._highlightsGain === -1) {
  68981. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68982. }
  68983. // Finish
  68984. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68985. if (cameras) {
  68986. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68987. }
  68988. return _this;
  68989. }
  68990. // public methods (self explanatory)
  68991. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68992. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68993. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68994. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68995. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68996. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68997. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68998. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68999. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  69000. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  69001. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  69002. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  69003. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  69004. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  69005. };
  69006. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  69007. this._highlightsPostProcess.updateEffect();
  69008. };
  69009. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  69010. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  69011. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  69012. this._highlightsGain = amount;
  69013. };
  69014. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  69015. if (this._highlightsGain === -1) {
  69016. this._highlightsGain = 1.0;
  69017. }
  69018. this._highlightsThreshold = amount;
  69019. };
  69020. LensRenderingPipeline.prototype.disableHighlights = function () {
  69021. this._highlightsGain = -1;
  69022. };
  69023. /**
  69024. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  69025. */
  69026. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  69027. if (disableDepthRender === void 0) { disableDepthRender = false; }
  69028. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69029. this._chromaticAberrationPostProcess = null;
  69030. this._highlightsPostProcess = null;
  69031. this._depthOfFieldPostProcess = null;
  69032. this._grainTexture.dispose();
  69033. if (disableDepthRender)
  69034. this._scene.disableDepthRenderer();
  69035. };
  69036. // colors shifting and distortion
  69037. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  69038. var _this = this;
  69039. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  69040. [], // samplers
  69041. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69042. this._chromaticAberrationPostProcess.onApply = function (effect) {
  69043. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  69044. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69045. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69046. effect.setFloat('radialIntensity', 1);
  69047. effect.setFloat2('direction', 17, 17);
  69048. effect.setFloat2('centerPosition', 0.5, 0.5);
  69049. };
  69050. };
  69051. // highlights enhancing
  69052. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  69053. var _this = this;
  69054. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  69055. [], // samplers
  69056. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  69057. this._highlightsPostProcess.onApply = function (effect) {
  69058. effect.setFloat('gain', _this._highlightsGain);
  69059. effect.setFloat('threshold', _this._highlightsThreshold);
  69060. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  69061. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69062. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69063. };
  69064. };
  69065. // colors shifting and distortion
  69066. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  69067. var _this = this;
  69068. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  69069. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  69070. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  69071. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69072. this._depthOfFieldPostProcess.onApply = function (effect) {
  69073. effect.setTexture("depthSampler", _this._depthTexture);
  69074. effect.setTexture("grainSampler", _this._grainTexture);
  69075. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  69076. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  69077. effect.setFloat('grain_amount', _this._grainAmount);
  69078. effect.setBool('blur_noise', _this._blurNoise);
  69079. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69080. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69081. effect.setFloat('distortion', _this._distortion);
  69082. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  69083. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  69084. effect.setFloat('aperture', _this._dofAperture);
  69085. effect.setFloat('darken', _this._dofDarken);
  69086. effect.setFloat('edge_blur', _this._edgeBlur);
  69087. effect.setBool('highlights', (_this._highlightsGain !== -1));
  69088. if (_this._scene.activeCamera) {
  69089. effect.setFloat('near', _this._scene.activeCamera.minZ);
  69090. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  69091. }
  69092. };
  69093. };
  69094. // creates a black and white random noise texture, 512x512
  69095. LensRenderingPipeline.prototype._createGrainTexture = function () {
  69096. var size = 512;
  69097. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69098. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69099. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69100. var context = this._grainTexture.getContext();
  69101. var rand = function (min, max) {
  69102. return Math.random() * (max - min) + min;
  69103. };
  69104. var value;
  69105. for (var x = 0; x < size; x++) {
  69106. for (var y = 0; y < size; y++) {
  69107. value = Math.floor(rand(0.42, 0.58) * 255);
  69108. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  69109. context.fillRect(x, y, 1, 1);
  69110. }
  69111. }
  69112. this._grainTexture.update(false);
  69113. };
  69114. return LensRenderingPipeline;
  69115. }(BABYLON.PostProcessRenderPipeline));
  69116. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  69117. })(BABYLON || (BABYLON = {}));
  69118. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  69119. "use strict";
  69120. var BABYLON;
  69121. (function (BABYLON) {
  69122. var StandardRenderingPipeline = /** @class */ (function (_super) {
  69123. __extends(StandardRenderingPipeline, _super);
  69124. /**
  69125. * @constructor
  69126. * @param {string} name - The rendering pipeline name
  69127. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69128. * @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)
  69129. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  69130. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69131. */
  69132. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  69133. if (originalPostProcess === void 0) { originalPostProcess = null; }
  69134. var _this = _super.call(this, scene.getEngine(), name) || this;
  69135. _this.downSampleX4PostProcess = null;
  69136. _this.brightPassPostProcess = null;
  69137. _this.blurHPostProcesses = [];
  69138. _this.blurVPostProcesses = [];
  69139. _this.textureAdderPostProcess = null;
  69140. _this.volumetricLightPostProcess = null;
  69141. _this.volumetricLightSmoothXPostProcess = null;
  69142. _this.volumetricLightSmoothYPostProcess = null;
  69143. _this.volumetricLightMergePostProces = null;
  69144. _this.volumetricLightFinalPostProcess = null;
  69145. _this.luminancePostProcess = null;
  69146. _this.luminanceDownSamplePostProcesses = [];
  69147. _this.hdrPostProcess = null;
  69148. _this.textureAdderFinalPostProcess = null;
  69149. _this.lensFlareFinalPostProcess = null;
  69150. _this.hdrFinalPostProcess = null;
  69151. _this.lensFlarePostProcess = null;
  69152. _this.lensFlareComposePostProcess = null;
  69153. _this.motionBlurPostProcess = null;
  69154. _this.depthOfFieldPostProcess = null;
  69155. // Values
  69156. _this.brightThreshold = 1.0;
  69157. _this.blurWidth = 512.0;
  69158. _this.horizontalBlur = false;
  69159. _this.exposure = 1.0;
  69160. _this.lensTexture = null;
  69161. _this.volumetricLightCoefficient = 0.2;
  69162. _this.volumetricLightPower = 4.0;
  69163. _this.volumetricLightBlurScale = 64.0;
  69164. _this.sourceLight = null;
  69165. _this.hdrMinimumLuminance = 1.0;
  69166. _this.hdrDecreaseRate = 0.5;
  69167. _this.hdrIncreaseRate = 0.5;
  69168. _this.lensColorTexture = null;
  69169. _this.lensFlareStrength = 20.0;
  69170. _this.lensFlareGhostDispersal = 1.4;
  69171. _this.lensFlareHaloWidth = 0.7;
  69172. _this.lensFlareDistortionStrength = 16.0;
  69173. _this.lensStarTexture = null;
  69174. _this.lensFlareDirtTexture = null;
  69175. _this.depthOfFieldDistance = 10.0;
  69176. _this.depthOfFieldBlurWidth = 64.0;
  69177. _this.motionStrength = 1.0;
  69178. // IAnimatable
  69179. _this.animations = [];
  69180. _this._currentDepthOfFieldSource = null;
  69181. _this._hdrCurrentLuminance = 1.0;
  69182. // Getters and setters
  69183. _this._bloomEnabled = true;
  69184. _this._depthOfFieldEnabled = false;
  69185. _this._vlsEnabled = false;
  69186. _this._lensFlareEnabled = false;
  69187. _this._hdrEnabled = false;
  69188. _this._motionBlurEnabled = false;
  69189. _this._motionBlurSamples = 64.0;
  69190. _this._volumetricLightStepsCount = 50.0;
  69191. _this._cameras = cameras || [];
  69192. // Initialize
  69193. _this._scene = scene;
  69194. _this._basePostProcess = originalPostProcess;
  69195. _this._ratio = ratio;
  69196. // Misc
  69197. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69198. // Finish
  69199. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69200. _this._buildPipeline();
  69201. return _this;
  69202. }
  69203. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  69204. get: function () {
  69205. return this._bloomEnabled;
  69206. },
  69207. set: function (enabled) {
  69208. if (this._bloomEnabled === enabled) {
  69209. return;
  69210. }
  69211. this._bloomEnabled = enabled;
  69212. this._buildPipeline();
  69213. },
  69214. enumerable: true,
  69215. configurable: true
  69216. });
  69217. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  69218. get: function () {
  69219. return this._depthOfFieldEnabled;
  69220. },
  69221. set: function (enabled) {
  69222. if (this._depthOfFieldEnabled === enabled) {
  69223. return;
  69224. }
  69225. this._depthOfFieldEnabled = enabled;
  69226. this._buildPipeline();
  69227. },
  69228. enumerable: true,
  69229. configurable: true
  69230. });
  69231. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  69232. get: function () {
  69233. return this._lensFlareEnabled;
  69234. },
  69235. set: function (enabled) {
  69236. if (this._lensFlareEnabled === enabled) {
  69237. return;
  69238. }
  69239. this._lensFlareEnabled = enabled;
  69240. this._buildPipeline();
  69241. },
  69242. enumerable: true,
  69243. configurable: true
  69244. });
  69245. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  69246. get: function () {
  69247. return this._hdrEnabled;
  69248. },
  69249. set: function (enabled) {
  69250. if (this._hdrEnabled === enabled) {
  69251. return;
  69252. }
  69253. this._hdrEnabled = enabled;
  69254. this._buildPipeline();
  69255. },
  69256. enumerable: true,
  69257. configurable: true
  69258. });
  69259. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  69260. get: function () {
  69261. return this._vlsEnabled;
  69262. },
  69263. set: function (enabled) {
  69264. if (this._vlsEnabled === enabled) {
  69265. return;
  69266. }
  69267. if (enabled) {
  69268. var geometry = this._scene.enableGeometryBufferRenderer();
  69269. if (!geometry) {
  69270. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  69271. return;
  69272. }
  69273. }
  69274. this._vlsEnabled = enabled;
  69275. this._buildPipeline();
  69276. },
  69277. enumerable: true,
  69278. configurable: true
  69279. });
  69280. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  69281. get: function () {
  69282. return this._motionBlurEnabled;
  69283. },
  69284. set: function (enabled) {
  69285. if (this._motionBlurEnabled === enabled) {
  69286. return;
  69287. }
  69288. this._motionBlurEnabled = enabled;
  69289. this._buildPipeline();
  69290. },
  69291. enumerable: true,
  69292. configurable: true
  69293. });
  69294. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  69295. get: function () {
  69296. return this._volumetricLightStepsCount;
  69297. },
  69298. set: function (count) {
  69299. if (this.volumetricLightPostProcess) {
  69300. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  69301. }
  69302. this._volumetricLightStepsCount = count;
  69303. },
  69304. enumerable: true,
  69305. configurable: true
  69306. });
  69307. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69308. get: function () {
  69309. return this._motionBlurSamples;
  69310. },
  69311. set: function (samples) {
  69312. if (this.motionBlurPostProcess) {
  69313. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69314. }
  69315. this._motionBlurSamples = samples;
  69316. },
  69317. enumerable: true,
  69318. configurable: true
  69319. });
  69320. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69321. var _this = this;
  69322. var ratio = this._ratio;
  69323. var scene = this._scene;
  69324. this._disposePostProcesses();
  69325. this._reset();
  69326. // Create pass post-process
  69327. if (!this._basePostProcess) {
  69328. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69329. this.originalPostProcess.onApply = function (effect) {
  69330. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69331. };
  69332. }
  69333. else {
  69334. this.originalPostProcess = this._basePostProcess;
  69335. }
  69336. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69337. this._currentDepthOfFieldSource = this.originalPostProcess;
  69338. if (this._vlsEnabled) {
  69339. // Create volumetric light
  69340. this._createVolumetricLightPostProcess(scene, ratio);
  69341. // Create volumetric light final post-process
  69342. 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);
  69343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69344. }
  69345. if (this._bloomEnabled) {
  69346. // Create down sample X4 post-process
  69347. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69348. // Create bright pass post-process
  69349. this._createBrightPassPostProcess(scene, ratio / 2);
  69350. // Create gaussian blur post-processes (down sampling blurs)
  69351. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69352. // Create texture adder post-process
  69353. this._createTextureAdderPostProcess(scene, ratio);
  69354. // Create depth-of-field source post-process
  69355. 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);
  69356. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69357. }
  69358. if (this._lensFlareEnabled) {
  69359. // Create lens flare post-process
  69360. this._createLensFlarePostProcess(scene, ratio);
  69361. // Create depth-of-field source post-process post lens-flare and disable it now
  69362. 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);
  69363. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69364. }
  69365. if (this._hdrEnabled) {
  69366. // Create luminance
  69367. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69368. // Create HDR
  69369. this._createHdrPostProcess(scene, ratio);
  69370. // Create depth-of-field source post-process post hdr and disable it now
  69371. 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);
  69372. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69373. }
  69374. if (this._depthOfFieldEnabled) {
  69375. // Create gaussian blur used by depth-of-field
  69376. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69377. // Create depth-of-field post-process
  69378. this._createDepthOfFieldPostProcess(scene, ratio);
  69379. }
  69380. if (this._motionBlurEnabled) {
  69381. // Create motion blur post-process
  69382. this._createMotionBlurPostProcess(scene, ratio);
  69383. }
  69384. if (this._cameras !== null) {
  69385. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69386. }
  69387. };
  69388. // Down Sample X4 Post-Processs
  69389. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69390. var _this = this;
  69391. var downSampleX4Offsets = new Array(32);
  69392. 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);
  69393. this.downSampleX4PostProcess.onApply = function (effect) {
  69394. var id = 0;
  69395. var width = _this.downSampleX4PostProcess.width;
  69396. var height = _this.downSampleX4PostProcess.height;
  69397. for (var i = -2; i < 2; i++) {
  69398. for (var j = -2; j < 2; j++) {
  69399. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69400. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69401. id += 2;
  69402. }
  69403. }
  69404. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69405. };
  69406. // Add to pipeline
  69407. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69408. };
  69409. // Brightpass Post-Process
  69410. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69411. var _this = this;
  69412. var brightOffsets = new Array(8);
  69413. 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);
  69414. this.brightPassPostProcess.onApply = function (effect) {
  69415. var sU = (1.0 / _this.brightPassPostProcess.width);
  69416. var sV = (1.0 / _this.brightPassPostProcess.height);
  69417. brightOffsets[0] = -0.5 * sU;
  69418. brightOffsets[1] = 0.5 * sV;
  69419. brightOffsets[2] = 0.5 * sU;
  69420. brightOffsets[3] = 0.5 * sV;
  69421. brightOffsets[4] = -0.5 * sU;
  69422. brightOffsets[5] = -0.5 * sV;
  69423. brightOffsets[6] = 0.5 * sU;
  69424. brightOffsets[7] = -0.5 * sV;
  69425. effect.setArray2("dsOffsets", brightOffsets);
  69426. effect.setFloat("brightThreshold", _this.brightThreshold);
  69427. };
  69428. // Add to pipeline
  69429. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69430. };
  69431. // Create blur H&V post-processes
  69432. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69433. var _this = this;
  69434. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69435. var engine = scene.getEngine();
  69436. 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);
  69437. 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);
  69438. blurX.onActivateObservable.add(function () {
  69439. var dw = blurX.width / engine.getRenderWidth();
  69440. blurX.kernel = _this[blurWidthKey] * dw;
  69441. });
  69442. blurY.onActivateObservable.add(function () {
  69443. var dw = blurY.height / engine.getRenderHeight();
  69444. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69445. });
  69446. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69447. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69448. this.blurHPostProcesses.push(blurX);
  69449. this.blurVPostProcesses.push(blurY);
  69450. };
  69451. // Create texture adder post-process
  69452. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69453. var _this = this;
  69454. 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);
  69455. this.textureAdderPostProcess.onApply = function (effect) {
  69456. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69457. effect.setTexture("lensSampler", _this.lensTexture);
  69458. effect.setFloat("exposure", _this.exposure);
  69459. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69460. };
  69461. // Add to pipeline
  69462. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69463. };
  69464. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69465. var _this = this;
  69466. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69467. geometryRenderer.enablePosition = true;
  69468. var geometry = geometryRenderer.getGBuffer();
  69469. // Base post-process
  69470. 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));
  69471. var depthValues = BABYLON.Vector2.Zero();
  69472. this.volumetricLightPostProcess.onApply = function (effect) {
  69473. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69474. var generator = _this.sourceLight.getShadowGenerator();
  69475. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69476. effect.setTexture("positionSampler", geometry.textures[2]);
  69477. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69478. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69479. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69480. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69481. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69482. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69483. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69484. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69485. effect.setVector2("depthValues", depthValues);
  69486. }
  69487. };
  69488. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69489. // Smooth
  69490. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69491. // Merge
  69492. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69493. this.volumetricLightMergePostProces.onApply = function (effect) {
  69494. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69495. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69496. };
  69497. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69498. };
  69499. // Create luminance
  69500. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69501. var _this = this;
  69502. // Create luminance
  69503. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69504. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69505. var offsets = [];
  69506. this.luminancePostProcess.onApply = function (effect) {
  69507. var sU = (1.0 / _this.luminancePostProcess.width);
  69508. var sV = (1.0 / _this.luminancePostProcess.height);
  69509. offsets[0] = -0.5 * sU;
  69510. offsets[1] = 0.5 * sV;
  69511. offsets[2] = 0.5 * sU;
  69512. offsets[3] = 0.5 * sV;
  69513. offsets[4] = -0.5 * sU;
  69514. offsets[5] = -0.5 * sV;
  69515. offsets[6] = 0.5 * sU;
  69516. offsets[7] = -0.5 * sV;
  69517. effect.setArray2("lumOffsets", offsets);
  69518. };
  69519. // Add to pipeline
  69520. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69521. // Create down sample luminance
  69522. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69523. var size = Math.pow(3, i);
  69524. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69525. if (i === 0) {
  69526. defines += "#define FINAL_DOWN_SAMPLER";
  69527. }
  69528. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69529. this.luminanceDownSamplePostProcesses.push(postProcess);
  69530. }
  69531. // Create callbacks and add effects
  69532. var lastLuminance = this.luminancePostProcess;
  69533. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69534. var downSampleOffsets = new Array(18);
  69535. pp.onApply = function (effect) {
  69536. if (!lastLuminance) {
  69537. return;
  69538. }
  69539. var id = 0;
  69540. for (var x = -1; x < 2; x++) {
  69541. for (var y = -1; y < 2; y++) {
  69542. downSampleOffsets[id] = x / lastLuminance.width;
  69543. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69544. id += 2;
  69545. }
  69546. }
  69547. effect.setArray2("dsOffsets", downSampleOffsets);
  69548. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69549. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69550. lastLuminance = _this.luminancePostProcess;
  69551. }
  69552. else {
  69553. lastLuminance = pp;
  69554. }
  69555. };
  69556. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69557. pp.onAfterRender = function (effect) {
  69558. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69559. 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);
  69560. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69561. };
  69562. }
  69563. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69564. });
  69565. };
  69566. // Create HDR post-process
  69567. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69568. var _this = this;
  69569. 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);
  69570. var outputLiminance = 1;
  69571. var time = 0;
  69572. var lastTime = 0;
  69573. this.hdrPostProcess.onApply = function (effect) {
  69574. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69575. time += scene.getEngine().getDeltaTime();
  69576. if (outputLiminance < 0) {
  69577. outputLiminance = _this._hdrCurrentLuminance;
  69578. }
  69579. else {
  69580. var dt = (lastTime - time) / 1000.0;
  69581. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69582. outputLiminance += _this.hdrDecreaseRate * dt;
  69583. }
  69584. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69585. outputLiminance -= _this.hdrIncreaseRate * dt;
  69586. }
  69587. else {
  69588. outputLiminance = _this._hdrCurrentLuminance;
  69589. }
  69590. }
  69591. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69592. effect.setFloat("averageLuminance", outputLiminance);
  69593. lastTime = time;
  69594. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69595. };
  69596. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69597. };
  69598. // Create lens flare post-process
  69599. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69600. var _this = this;
  69601. 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);
  69602. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69603. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69604. 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);
  69605. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69606. var resolution = new BABYLON.Vector2(0, 0);
  69607. // Lens flare
  69608. this.lensFlarePostProcess.onApply = function (effect) {
  69609. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69610. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69611. effect.setFloat("strength", _this.lensFlareStrength);
  69612. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69613. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69614. // Shift
  69615. resolution.x = _this.lensFlarePostProcess.width;
  69616. resolution.y = _this.lensFlarePostProcess.height;
  69617. effect.setVector2("resolution", resolution);
  69618. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69619. };
  69620. // Compose
  69621. 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);
  69622. 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);
  69623. this.lensFlareComposePostProcess.onApply = function (effect) {
  69624. if (!_this._scene.activeCamera) {
  69625. return;
  69626. }
  69627. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69628. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69629. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69630. // Lens start rotation matrix
  69631. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69632. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69633. 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));
  69634. camRot *= 4.0;
  69635. 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);
  69636. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69637. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69638. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69639. };
  69640. };
  69641. // Create depth-of-field post-process
  69642. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69643. var _this = this;
  69644. 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);
  69645. this.depthOfFieldPostProcess.onApply = function (effect) {
  69646. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69647. effect.setTexture("depthSampler", _this._getDepthTexture());
  69648. effect.setFloat("distance", _this.depthOfFieldDistance);
  69649. };
  69650. // Add to pipeline
  69651. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69652. };
  69653. // Create motion blur post-process
  69654. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69655. var _this = this;
  69656. 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);
  69657. var motionScale = 0;
  69658. var prevViewProjection = BABYLON.Matrix.Identity();
  69659. var invViewProjection = BABYLON.Matrix.Identity();
  69660. var viewProjection = BABYLON.Matrix.Identity();
  69661. var screenSize = BABYLON.Vector2.Zero();
  69662. this.motionBlurPostProcess.onApply = function (effect) {
  69663. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69664. viewProjection.invertToRef(invViewProjection);
  69665. effect.setMatrix("inverseViewProjection", invViewProjection);
  69666. effect.setMatrix("prevViewProjection", prevViewProjection);
  69667. prevViewProjection = viewProjection;
  69668. screenSize.x = _this.motionBlurPostProcess.width;
  69669. screenSize.y = _this.motionBlurPostProcess.height;
  69670. effect.setVector2("screenSize", screenSize);
  69671. motionScale = scene.getEngine().getFps() / 60.0;
  69672. effect.setFloat("motionScale", motionScale);
  69673. effect.setFloat("motionStrength", _this.motionStrength);
  69674. effect.setTexture("depthSampler", _this._getDepthTexture());
  69675. };
  69676. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69677. };
  69678. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69679. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69680. var renderer = this._scene.enableGeometryBufferRenderer();
  69681. return renderer.getGBuffer().textures[0];
  69682. }
  69683. return this._scene.enableDepthRenderer().getDepthMap();
  69684. };
  69685. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69686. for (var i = 0; i < this._cameras.length; i++) {
  69687. var camera = this._cameras[i];
  69688. if (this.originalPostProcess) {
  69689. this.originalPostProcess.dispose(camera);
  69690. }
  69691. if (this.downSampleX4PostProcess) {
  69692. this.downSampleX4PostProcess.dispose(camera);
  69693. }
  69694. if (this.brightPassPostProcess) {
  69695. this.brightPassPostProcess.dispose(camera);
  69696. }
  69697. if (this.textureAdderPostProcess) {
  69698. this.textureAdderPostProcess.dispose(camera);
  69699. }
  69700. if (this.textureAdderFinalPostProcess) {
  69701. this.textureAdderFinalPostProcess.dispose(camera);
  69702. }
  69703. if (this.volumetricLightPostProcess) {
  69704. this.volumetricLightPostProcess.dispose(camera);
  69705. }
  69706. if (this.volumetricLightSmoothXPostProcess) {
  69707. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69708. }
  69709. if (this.volumetricLightSmoothYPostProcess) {
  69710. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69711. }
  69712. if (this.volumetricLightMergePostProces) {
  69713. this.volumetricLightMergePostProces.dispose(camera);
  69714. }
  69715. if (this.volumetricLightFinalPostProcess) {
  69716. this.volumetricLightFinalPostProcess.dispose(camera);
  69717. }
  69718. if (this.lensFlarePostProcess) {
  69719. this.lensFlarePostProcess.dispose(camera);
  69720. }
  69721. if (this.lensFlareComposePostProcess) {
  69722. this.lensFlareComposePostProcess.dispose(camera);
  69723. }
  69724. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69725. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69726. }
  69727. if (this.luminancePostProcess) {
  69728. this.luminancePostProcess.dispose(camera);
  69729. }
  69730. if (this.hdrPostProcess) {
  69731. this.hdrPostProcess.dispose(camera);
  69732. }
  69733. if (this.hdrFinalPostProcess) {
  69734. this.hdrFinalPostProcess.dispose(camera);
  69735. }
  69736. if (this.depthOfFieldPostProcess) {
  69737. this.depthOfFieldPostProcess.dispose(camera);
  69738. }
  69739. if (this.motionBlurPostProcess) {
  69740. this.motionBlurPostProcess.dispose(camera);
  69741. }
  69742. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69743. this.blurHPostProcesses[j].dispose(camera);
  69744. }
  69745. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69746. this.blurVPostProcesses[j].dispose(camera);
  69747. }
  69748. }
  69749. this.originalPostProcess = null;
  69750. this.downSampleX4PostProcess = null;
  69751. this.brightPassPostProcess = null;
  69752. this.textureAdderPostProcess = null;
  69753. this.textureAdderFinalPostProcess = null;
  69754. this.volumetricLightPostProcess = null;
  69755. this.volumetricLightSmoothXPostProcess = null;
  69756. this.volumetricLightSmoothYPostProcess = null;
  69757. this.volumetricLightMergePostProces = null;
  69758. this.volumetricLightFinalPostProcess = null;
  69759. this.lensFlarePostProcess = null;
  69760. this.lensFlareComposePostProcess = null;
  69761. this.luminancePostProcess = null;
  69762. this.hdrPostProcess = null;
  69763. this.hdrFinalPostProcess = null;
  69764. this.depthOfFieldPostProcess = null;
  69765. this.motionBlurPostProcess = null;
  69766. this.luminanceDownSamplePostProcesses = [];
  69767. this.blurHPostProcesses = [];
  69768. this.blurVPostProcesses = [];
  69769. };
  69770. // Dispose
  69771. StandardRenderingPipeline.prototype.dispose = function () {
  69772. this._disposePostProcesses();
  69773. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69774. _super.prototype.dispose.call(this);
  69775. };
  69776. // Serialize rendering pipeline
  69777. StandardRenderingPipeline.prototype.serialize = function () {
  69778. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69779. serializationObject.customType = "StandardRenderingPipeline";
  69780. return serializationObject;
  69781. };
  69782. /**
  69783. * Static members
  69784. */
  69785. // Parse serialized pipeline
  69786. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69787. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69788. };
  69789. // Luminance steps
  69790. StandardRenderingPipeline.LuminanceSteps = 6;
  69791. __decorate([
  69792. BABYLON.serialize()
  69793. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69794. __decorate([
  69795. BABYLON.serialize()
  69796. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69797. __decorate([
  69798. BABYLON.serialize()
  69799. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69800. __decorate([
  69801. BABYLON.serialize()
  69802. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69803. __decorate([
  69804. BABYLON.serializeAsTexture("lensTexture")
  69805. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69806. __decorate([
  69807. BABYLON.serialize()
  69808. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69809. __decorate([
  69810. BABYLON.serialize()
  69811. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69812. __decorate([
  69813. BABYLON.serialize()
  69814. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69815. __decorate([
  69816. BABYLON.serialize()
  69817. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69818. __decorate([
  69819. BABYLON.serialize()
  69820. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69821. __decorate([
  69822. BABYLON.serialize()
  69823. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69824. __decorate([
  69825. BABYLON.serializeAsTexture("lensColorTexture")
  69826. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69827. __decorate([
  69828. BABYLON.serialize()
  69829. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69830. __decorate([
  69831. BABYLON.serialize()
  69832. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69833. __decorate([
  69834. BABYLON.serialize()
  69835. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69836. __decorate([
  69837. BABYLON.serialize()
  69838. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69839. __decorate([
  69840. BABYLON.serializeAsTexture("lensStarTexture")
  69841. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69842. __decorate([
  69843. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69844. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69845. __decorate([
  69846. BABYLON.serialize()
  69847. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69848. __decorate([
  69849. BABYLON.serialize()
  69850. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69851. __decorate([
  69852. BABYLON.serialize()
  69853. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69854. __decorate([
  69855. BABYLON.serialize()
  69856. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69857. __decorate([
  69858. BABYLON.serialize()
  69859. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69860. __decorate([
  69861. BABYLON.serialize()
  69862. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69863. __decorate([
  69864. BABYLON.serialize()
  69865. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69866. __decorate([
  69867. BABYLON.serialize()
  69868. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69869. __decorate([
  69870. BABYLON.serialize()
  69871. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69872. __decorate([
  69873. BABYLON.serialize()
  69874. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69875. __decorate([
  69876. BABYLON.serialize()
  69877. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69878. __decorate([
  69879. BABYLON.serialize()
  69880. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69881. return StandardRenderingPipeline;
  69882. }(BABYLON.PostProcessRenderPipeline));
  69883. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69884. })(BABYLON || (BABYLON = {}));
  69885. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69886. "use strict";
  69887. var BABYLON;
  69888. (function (BABYLON) {
  69889. var FxaaPostProcess = /** @class */ (function (_super) {
  69890. __extends(FxaaPostProcess, _super);
  69891. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69892. if (camera === void 0) { camera = null; }
  69893. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69894. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69895. _this.onApplyObservable.add(function (effect) {
  69896. var texelSize = _this.texelSize;
  69897. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69898. });
  69899. return _this;
  69900. }
  69901. return FxaaPostProcess;
  69902. }(BABYLON.PostProcess));
  69903. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69904. })(BABYLON || (BABYLON = {}));
  69905. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69906. "use strict";
  69907. var BABYLON;
  69908. (function (BABYLON) {
  69909. /**
  69910. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69911. */
  69912. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69913. __extends(ChromaticAberrationPostProcess, _super);
  69914. /**
  69915. * Creates a new instance of @see ChromaticAberrationPostProcess
  69916. * @param name The name of the effect.
  69917. * @param screenWidth The width of the screen to apply the effect on.
  69918. * @param screenHeight The height of the screen to apply the effect on.
  69919. * @param options The required width/height ratio to downsize to before computing the render pass.
  69920. * @param camera The camera to apply the render pass to.
  69921. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69922. * @param engine The engine which the post process will be applied. (default: current engine)
  69923. * @param reusable If the post process can be reused on the same frame. (default: false)
  69924. * @param textureType Type of textures used when performing the post process. (default: 0)
  69925. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69926. */
  69927. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69928. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69929. if (blockCompilation === void 0) { blockCompilation = false; }
  69930. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69931. /**
  69932. * The amount of seperation of rgb channels (default: 30)
  69933. */
  69934. _this.aberrationAmount = 30;
  69935. /**
  69936. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69937. */
  69938. _this.radialIntensity = 0;
  69939. /**
  69940. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  69941. */
  69942. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69943. /**
  69944. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  69945. */
  69946. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69947. _this.onApplyObservable.add(function (effect) {
  69948. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69949. effect.setFloat('screen_width', screenWidth);
  69950. effect.setFloat('screen_height', screenHeight);
  69951. effect.setFloat('radialIntensity', _this.radialIntensity);
  69952. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69953. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69954. });
  69955. return _this;
  69956. }
  69957. return ChromaticAberrationPostProcess;
  69958. }(BABYLON.PostProcess));
  69959. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69960. })(BABYLON || (BABYLON = {}));
  69961. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69962. "use strict";
  69963. var BABYLON;
  69964. (function (BABYLON) {
  69965. /**
  69966. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69967. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69968. */
  69969. var SharpenPostProcess = /** @class */ (function (_super) {
  69970. __extends(SharpenPostProcess, _super);
  69971. /**
  69972. * Creates a new instance of @see ConvolutionPostProcess
  69973. * @param name The name of the effect.
  69974. * @param options The required width/height ratio to downsize to before computing the render pass.
  69975. * @param camera The camera to apply the render pass to.
  69976. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69977. * @param engine The engine which the post process will be applied. (default: current engine)
  69978. * @param reusable If the post process can be reused on the same frame. (default: false)
  69979. * @param textureType Type of textures used when performing the post process. (default: 0)
  69980. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69981. */
  69982. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69983. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69984. if (blockCompilation === void 0) { blockCompilation = false; }
  69985. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69986. /**
  69987. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69988. */
  69989. _this.colorAmount = 1.0;
  69990. /**
  69991. * How much sharpness should be applied (default: 0.3)
  69992. */
  69993. _this.edgeAmount = 0.3;
  69994. _this.onApply = function (effect) {
  69995. effect.setFloat2("screenSize", _this.width, _this.height);
  69996. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69997. };
  69998. return _this;
  69999. }
  70000. return SharpenPostProcess;
  70001. }(BABYLON.PostProcess));
  70002. BABYLON.SharpenPostProcess = SharpenPostProcess;
  70003. })(BABYLON || (BABYLON = {}));
  70004. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  70005. "use strict";
  70006. var BABYLON;
  70007. (function (BABYLON) {
  70008. /**
  70009. * The Blur Post Process which blurs an image based on a kernel and direction.
  70010. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  70011. */
  70012. var BlurPostProcess = /** @class */ (function (_super) {
  70013. __extends(BlurPostProcess, _super);
  70014. /**
  70015. * Creates a new instance of @see BlurPostProcess
  70016. * @param name The name of the effect.
  70017. * @param direction The direction in which to blur the image.
  70018. * @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.
  70019. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70020. * @param camera The camera to apply the render pass to.
  70021. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70022. * @param engine The engine which the post process will be applied. (default: current engine)
  70023. * @param reusable If the post process can be reused on the same frame. (default: false)
  70024. * @param textureType Type of textures used when performing the post process. (default: 0)
  70025. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70026. */
  70027. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  70028. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70029. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70030. if (defines === void 0) { defines = ""; }
  70031. if (blockCompilation === void 0) { blockCompilation = false; }
  70032. 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;
  70033. _this.direction = direction;
  70034. _this.blockCompilation = blockCompilation;
  70035. _this._packedFloat = false;
  70036. _this._staticDefines = "";
  70037. _this._staticDefines = defines;
  70038. _this.onApplyObservable.add(function (effect) {
  70039. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70040. });
  70041. _this.kernel = kernel;
  70042. return _this;
  70043. }
  70044. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70045. /**
  70046. * Gets the length in pixels of the blur sample region
  70047. */
  70048. get: function () {
  70049. return this._idealKernel;
  70050. },
  70051. /**
  70052. * Sets the length in pixels of the blur sample region
  70053. */
  70054. set: function (v) {
  70055. if (this._idealKernel === v) {
  70056. return;
  70057. }
  70058. v = Math.max(v, 1);
  70059. this._idealKernel = v;
  70060. this._kernel = this._nearestBestKernel(v);
  70061. if (!this.blockCompilation) {
  70062. this._updateParameters();
  70063. }
  70064. },
  70065. enumerable: true,
  70066. configurable: true
  70067. });
  70068. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70069. /**
  70070. * Gets wether or not the blur is unpacking/repacking floats
  70071. */
  70072. get: function () {
  70073. return this._packedFloat;
  70074. },
  70075. /**
  70076. * Sets wether or not the blur needs to unpack/repack floats
  70077. */
  70078. set: function (v) {
  70079. if (this._packedFloat === v) {
  70080. return;
  70081. }
  70082. this._packedFloat = v;
  70083. if (!this.blockCompilation) {
  70084. this._updateParameters();
  70085. }
  70086. },
  70087. enumerable: true,
  70088. configurable: true
  70089. });
  70090. /**
  70091. * Updates the effect with the current post process compile time values and recompiles the shader.
  70092. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70093. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70094. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70095. * @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
  70096. * @param onCompiled Called when the shader has been compiled.
  70097. * @param onError Called if there is an error when compiling a shader.
  70098. */
  70099. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70100. if (defines === void 0) { defines = null; }
  70101. if (uniforms === void 0) { uniforms = null; }
  70102. if (samplers === void 0) { samplers = null; }
  70103. this._updateParameters(onCompiled, onError);
  70104. };
  70105. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  70106. // Generate sampling offsets and weights
  70107. var N = this._kernel;
  70108. var centerIndex = (N - 1) / 2;
  70109. // Generate Gaussian sampling weights over kernel
  70110. var offsets = [];
  70111. var weights = [];
  70112. var totalWeight = 0;
  70113. for (var i = 0; i < N; i++) {
  70114. var u = i / (N - 1);
  70115. var w = this._gaussianWeight(u * 2.0 - 1);
  70116. offsets[i] = (i - centerIndex);
  70117. weights[i] = w;
  70118. totalWeight += w;
  70119. }
  70120. // Normalize weights
  70121. for (var i = 0; i < weights.length; i++) {
  70122. weights[i] /= totalWeight;
  70123. }
  70124. // Optimize: combine samples to take advantage of hardware linear sampling
  70125. // Walk from left to center, combining pairs (symmetrically)
  70126. var linearSamplingWeights = [];
  70127. var linearSamplingOffsets = [];
  70128. var linearSamplingMap = [];
  70129. for (var i = 0; i <= centerIndex; i += 2) {
  70130. var j = Math.min(i + 1, Math.floor(centerIndex));
  70131. var singleCenterSample = i === j;
  70132. if (singleCenterSample) {
  70133. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70134. }
  70135. else {
  70136. var sharedCell = j === centerIndex;
  70137. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70138. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70139. if (offsetLinear === 0) {
  70140. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70141. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70142. }
  70143. else {
  70144. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70145. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70146. }
  70147. }
  70148. }
  70149. for (var i = 0; i < linearSamplingMap.length; i++) {
  70150. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70151. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70152. }
  70153. // Replace with optimized
  70154. offsets = linearSamplingOffsets;
  70155. weights = linearSamplingWeights;
  70156. // Generate shaders
  70157. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70158. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70159. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70160. var defines = "";
  70161. defines += this._staticDefines;
  70162. for (var i = 0; i < varyingCount; i++) {
  70163. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70164. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70165. }
  70166. var depCount = 0;
  70167. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70168. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70169. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70170. depCount++;
  70171. }
  70172. if (this.packedFloat) {
  70173. defines += "#define PACKEDFLOAT 1";
  70174. }
  70175. _super.prototype.updateEffect.call(this, defines, null, null, {
  70176. varyingCount: varyingCount,
  70177. depCount: depCount
  70178. }, onCompiled, onError);
  70179. };
  70180. /**
  70181. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70182. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70183. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70184. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70185. * The gaps between physical kernels are compensated for in the weighting of the samples
  70186. * @param idealKernel Ideal blur kernel.
  70187. * @return Nearest best kernel.
  70188. */
  70189. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70190. var v = Math.round(idealKernel);
  70191. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70192. var k = _a[_i];
  70193. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70194. return Math.max(k, 3);
  70195. }
  70196. }
  70197. return Math.max(v, 3);
  70198. };
  70199. /**
  70200. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70201. * @param x The point on the Gaussian distribution to sample.
  70202. * @return the value of the Gaussian function at x.
  70203. */
  70204. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70205. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70206. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70207. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70208. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70209. // truncated at around 1.3% of peak strength.
  70210. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70211. var sigma = (1 / 3);
  70212. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70213. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70214. var weight = (1.0 / denominator) * Math.exp(exponent);
  70215. return weight;
  70216. };
  70217. /**
  70218. * Generates a string that can be used as a floating point number in GLSL.
  70219. * @param x Value to print.
  70220. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70221. * @return GLSL float string.
  70222. */
  70223. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70224. if (decimalFigures === void 0) { decimalFigures = 8; }
  70225. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70226. };
  70227. return BlurPostProcess;
  70228. }(BABYLON.PostProcess));
  70229. BABYLON.BlurPostProcess = BlurPostProcess;
  70230. })(BABYLON || (BABYLON = {}));
  70231. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70232. "use strict";
  70233. var BABYLON;
  70234. (function (BABYLON) {
  70235. /**
  70236. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70237. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70238. * based on samples that have a large difference in distance than the center pixel.
  70239. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70240. */
  70241. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70242. __extends(DepthOfFieldBlurPostProcess, _super);
  70243. /**
  70244. * Creates a new instance of @see CircleOfConfusionPostProcess
  70245. * @param name The name of the effect.
  70246. * @param scene The scene the effect belongs to.
  70247. * @param direction The direction the blur should be applied.
  70248. * @param kernel The size of the kernel used to blur.
  70249. * @param options The required width/height ratio to downsize to before computing the render pass.
  70250. * @param camera The camera to apply the render pass to.
  70251. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70252. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70253. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70254. * @param engine The engine which the post process will be applied. (default: current engine)
  70255. * @param reusable If the post process can be reused on the same frame. (default: false)
  70256. * @param textureType Type of textures used when performing the post process. (default: 0)
  70257. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70258. */
  70259. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  70260. if (imageToBlur === void 0) { imageToBlur = null; }
  70261. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70262. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70263. if (blockCompilation === void 0) { blockCompilation = false; }
  70264. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  70265. _this.direction = direction;
  70266. _this.onApplyObservable.add(function (effect) {
  70267. if (imageToBlur != null) {
  70268. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70269. }
  70270. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70271. if (scene.activeCamera) {
  70272. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70273. }
  70274. });
  70275. return _this;
  70276. }
  70277. return DepthOfFieldBlurPostProcess;
  70278. }(BABYLON.BlurPostProcess));
  70279. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70280. })(BABYLON || (BABYLON = {}));
  70281. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70282. "use strict";
  70283. var BABYLON;
  70284. (function (BABYLON) {
  70285. /**
  70286. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70287. */
  70288. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  70289. __extends(DepthOfFieldMergePostProcess, _super);
  70290. /**
  70291. * Creates a new instance of @see CircleOfConfusionPostProcess
  70292. * @param name The name of the effect.
  70293. * @param original The non-blurred image to be modified
  70294. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  70295. * @param blurSteps Incrimental bluring post processes.
  70296. * @param options The required width/height ratio to downsize to before computing the render pass.
  70297. * @param camera The camera to apply the render pass to.
  70298. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70299. * @param engine The engine which the post process will be applied. (default: current engine)
  70300. * @param reusable If the post process can be reused on the same frame. (default: false)
  70301. * @param textureType Type of textures used when performing the post process. (default: 0)
  70302. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70303. */
  70304. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70305. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70306. if (blockCompilation === void 0) { blockCompilation = false; }
  70307. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70308. _this.blurSteps = blurSteps;
  70309. _this.onApplyObservable.add(function (effect) {
  70310. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70311. effect.setTextureFromPostProcess("textureSampler", original);
  70312. blurSteps.forEach(function (step, index) {
  70313. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70314. });
  70315. });
  70316. if (!blockCompilation) {
  70317. _this.updateEffect();
  70318. }
  70319. return _this;
  70320. }
  70321. /**
  70322. * Updates the effect with the current post process compile time values and recompiles the shader.
  70323. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70324. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70325. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70326. * @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
  70327. * @param onCompiled Called when the shader has been compiled.
  70328. * @param onError Called if there is an error when compiling a shader.
  70329. */
  70330. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70331. if (defines === void 0) { defines = null; }
  70332. if (uniforms === void 0) { uniforms = null; }
  70333. if (samplers === void 0) { samplers = null; }
  70334. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  70335. };
  70336. return DepthOfFieldMergePostProcess;
  70337. }(BABYLON.PostProcess));
  70338. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70339. })(BABYLON || (BABYLON = {}));
  70340. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70341. "use strict";
  70342. var BABYLON;
  70343. (function (BABYLON) {
  70344. /**
  70345. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70346. */
  70347. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70348. __extends(CircleOfConfusionPostProcess, _super);
  70349. /**
  70350. * Creates a new instance of @see CircleOfConfusionPostProcess
  70351. * @param name The name of the effect.
  70352. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  70353. * @param options The required width/height ratio to downsize to before computing the render pass.
  70354. * @param camera The camera to apply the render pass to.
  70355. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70356. * @param engine The engine which the post process will be applied. (default: current engine)
  70357. * @param reusable If the post process can be reused on the same frame. (default: false)
  70358. * @param textureType Type of textures used when performing the post process. (default: 0)
  70359. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70360. */
  70361. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70362. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70363. if (blockCompilation === void 0) { blockCompilation = false; }
  70364. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70365. /**
  70366. * 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.
  70367. */
  70368. _this.lensSize = 50;
  70369. /**
  70370. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70371. */
  70372. _this.fStop = 1.4;
  70373. /**
  70374. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70375. */
  70376. _this.focusDistance = 2000;
  70377. /**
  70378. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70379. */
  70380. _this.focalLength = 50;
  70381. _this._depthTexture = null;
  70382. _this._depthTexture = depthTexture;
  70383. _this.onApplyObservable.add(function (effect) {
  70384. if (!_this._depthTexture) {
  70385. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70386. return;
  70387. }
  70388. effect.setTexture("depthSampler", _this._depthTexture);
  70389. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70390. var aperture = _this.lensSize / _this.fStop;
  70391. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70392. effect.setFloat('focusDistance', _this.focusDistance);
  70393. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70394. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70395. });
  70396. return _this;
  70397. }
  70398. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70399. /**
  70400. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  70401. */
  70402. set: function (value) {
  70403. this._depthTexture = value;
  70404. },
  70405. enumerable: true,
  70406. configurable: true
  70407. });
  70408. return CircleOfConfusionPostProcess;
  70409. }(BABYLON.PostProcess));
  70410. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70411. })(BABYLON || (BABYLON = {}));
  70412. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70413. "use strict";
  70414. var BABYLON;
  70415. (function (BABYLON) {
  70416. /**
  70417. * Specifies the level of max blur that should be applied when using the depth of field effect
  70418. */
  70419. var DepthOfFieldEffectBlurLevel;
  70420. (function (DepthOfFieldEffectBlurLevel) {
  70421. /**
  70422. * Subtle blur
  70423. */
  70424. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70425. /**
  70426. * Medium blur
  70427. */
  70428. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70429. /**
  70430. * Large blur
  70431. */
  70432. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70433. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70434. ;
  70435. /**
  70436. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70437. */
  70438. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70439. __extends(DepthOfFieldEffect, _super);
  70440. /**
  70441. * Creates a new instance of @see DepthOfFieldEffect
  70442. * @param scene The scene the effect belongs to.
  70443. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  70444. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70445. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70446. */
  70447. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70448. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70449. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70450. if (blockCompilation === void 0) { blockCompilation = false; }
  70451. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70452. return _this._effects;
  70453. }, true) || this;
  70454. _this._effects = [];
  70455. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70456. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70457. // 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)
  70458. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70459. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70460. _this._depthOfFieldBlurY = [];
  70461. _this._depthOfFieldBlurX = [];
  70462. var blurCount = 1;
  70463. var kernelSize = 15;
  70464. switch (blurLevel) {
  70465. case DepthOfFieldEffectBlurLevel.High: {
  70466. blurCount = 3;
  70467. kernelSize = 51;
  70468. break;
  70469. }
  70470. case DepthOfFieldEffectBlurLevel.Medium: {
  70471. blurCount = 2;
  70472. kernelSize = 31;
  70473. break;
  70474. }
  70475. default: {
  70476. kernelSize = 15;
  70477. blurCount = 1;
  70478. break;
  70479. }
  70480. }
  70481. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70482. for (var i = 0; i < blurCount; i++) {
  70483. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70484. blurY.autoClear = false;
  70485. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70486. blurX.autoClear = false;
  70487. _this._depthOfFieldBlurY.push(blurY);
  70488. _this._depthOfFieldBlurX.push(blurX);
  70489. }
  70490. // Merge blurred images with original image based on circleOfConfusion
  70491. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70492. _this._depthOfFieldMerge.autoClear = false;
  70493. // Set all post processes on the effect.
  70494. _this._effects = [_this._circleOfConfusion];
  70495. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70496. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70497. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70498. }
  70499. _this._effects.push(_this._depthOfFieldMerge);
  70500. return _this;
  70501. }
  70502. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70503. get: function () {
  70504. return this._circleOfConfusion.focalLength;
  70505. },
  70506. /**
  70507. * The focal the length of the camera used in the effect
  70508. */
  70509. set: function (value) {
  70510. this._circleOfConfusion.focalLength = value;
  70511. },
  70512. enumerable: true,
  70513. configurable: true
  70514. });
  70515. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70516. get: function () {
  70517. return this._circleOfConfusion.fStop;
  70518. },
  70519. /**
  70520. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70521. */
  70522. set: function (value) {
  70523. this._circleOfConfusion.fStop = value;
  70524. },
  70525. enumerable: true,
  70526. configurable: true
  70527. });
  70528. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70529. get: function () {
  70530. return this._circleOfConfusion.focusDistance;
  70531. },
  70532. /**
  70533. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70534. */
  70535. set: function (value) {
  70536. this._circleOfConfusion.focusDistance = value;
  70537. },
  70538. enumerable: true,
  70539. configurable: true
  70540. });
  70541. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70542. get: function () {
  70543. return this._circleOfConfusion.lensSize;
  70544. },
  70545. /**
  70546. * 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.
  70547. */
  70548. set: function (value) {
  70549. this._circleOfConfusion.lensSize = value;
  70550. },
  70551. enumerable: true,
  70552. configurable: true
  70553. });
  70554. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70555. /**
  70556. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  70557. */
  70558. set: function (value) {
  70559. this._circleOfConfusion.depthTexture = value;
  70560. },
  70561. enumerable: true,
  70562. configurable: true
  70563. });
  70564. /**
  70565. * Disposes each of the internal effects for a given camera.
  70566. * @param camera The camera to dispose the effect on.
  70567. */
  70568. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70569. this._circleOfConfusion.dispose(camera);
  70570. this._depthOfFieldBlurX.forEach(function (element) {
  70571. element.dispose(camera);
  70572. });
  70573. this._depthOfFieldBlurY.forEach(function (element) {
  70574. element.dispose(camera);
  70575. });
  70576. this._depthOfFieldMerge.dispose(camera);
  70577. };
  70578. /**
  70579. * Internal
  70580. */
  70581. DepthOfFieldEffect.prototype._updateEffects = function () {
  70582. for (var effect in this._effects) {
  70583. this._effects[effect].updateEffect();
  70584. }
  70585. };
  70586. /**
  70587. * Internal
  70588. * @returns if all the contained post processes are ready.
  70589. */
  70590. DepthOfFieldEffect.prototype._isReady = function () {
  70591. for (var effect in this._effects) {
  70592. if (!this._effects[effect].isReady()) {
  70593. return false;
  70594. }
  70595. }
  70596. return true;
  70597. };
  70598. return DepthOfFieldEffect;
  70599. }(BABYLON.PostProcessRenderEffect));
  70600. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70601. })(BABYLON || (BABYLON = {}));
  70602. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70603. "use strict";
  70604. var BABYLON;
  70605. (function (BABYLON) {
  70606. /**
  70607. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70608. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70609. */
  70610. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70611. __extends(DefaultRenderingPipeline, _super);
  70612. /**
  70613. * @constructor
  70614. * @param {string} name - The rendering pipeline name
  70615. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70616. * @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)
  70617. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70618. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70619. */
  70620. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70621. if (automaticBuild === void 0) { automaticBuild = true; }
  70622. var _this = _super.call(this, scene.getEngine(), name) || this;
  70623. _this._originalCameras = [];
  70624. /**
  70625. * ID of the sharpen post process,
  70626. */
  70627. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70628. /**
  70629. * ID of the pass post process used for bloom,
  70630. */
  70631. _this.PassPostProcessId = "PassPostProcessEffect";
  70632. /**
  70633. * ID of the highlight post process used for bloom,
  70634. */
  70635. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  70636. /**
  70637. * ID of the blurX post process used for bloom,
  70638. */
  70639. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  70640. /**
  70641. * ID of the blurY post process used for bloom,
  70642. */
  70643. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  70644. /**
  70645. * ID of the copy back post process used for bloom,
  70646. */
  70647. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  70648. /**
  70649. * ID of the image processing post process;
  70650. */
  70651. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70652. /**
  70653. * ID of the Fast Approximate Anti-Aliasing post process;
  70654. */
  70655. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70656. /**
  70657. * ID of the final merge post process;
  70658. */
  70659. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70660. /**
  70661. * ID of the chromatic aberration post process,
  70662. */
  70663. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70664. /**
  70665. * Animations which can be used to tweak settings over a period of time
  70666. */
  70667. _this.animations = [];
  70668. // Values
  70669. _this._sharpenEnabled = false;
  70670. _this._bloomEnabled = false;
  70671. _this._depthOfFieldEnabled = false;
  70672. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70673. _this._fxaaEnabled = false;
  70674. _this._msaaEnabled = false;
  70675. _this._imageProcessingEnabled = true;
  70676. _this._bloomScale = 0.6;
  70677. _this._chromaticAberrationEnabled = false;
  70678. _this._buildAllowed = true;
  70679. /**
  70680. * Specifies the size of the bloom blur kernel, relative to the final output size
  70681. */
  70682. _this.bloomKernel = 64;
  70683. /**
  70684. * Specifies the weight of the bloom in the final rendering
  70685. */
  70686. _this._bloomWeight = 0.15;
  70687. _this._prevPostProcess = null;
  70688. _this._prevPrevPostProcess = null;
  70689. _this._cameras = cameras || [];
  70690. _this._originalCameras = _this._cameras.slice();
  70691. _this._buildAllowed = automaticBuild;
  70692. // Initialize
  70693. _this._scene = scene;
  70694. var caps = _this._scene.getEngine().getCaps();
  70695. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70696. // Misc
  70697. if (_this._hdr) {
  70698. if (caps.textureHalfFloatRender) {
  70699. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70700. }
  70701. else if (caps.textureFloatRender) {
  70702. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70703. }
  70704. }
  70705. else {
  70706. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70707. }
  70708. // Attach
  70709. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70710. var engine = _this._scene.getEngine();
  70711. // Create post processes before hand so they can be modified before enabled.
  70712. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70713. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70714. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70715. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70716. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70717. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70718. _this._buildPipeline();
  70719. return _this;
  70720. }
  70721. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70722. get: function () {
  70723. return this._sharpenEnabled;
  70724. },
  70725. /**
  70726. * Enable or disable the sharpen process from the pipeline
  70727. */
  70728. set: function (enabled) {
  70729. if (this._sharpenEnabled === enabled) {
  70730. return;
  70731. }
  70732. this._sharpenEnabled = enabled;
  70733. this._buildPipeline();
  70734. },
  70735. enumerable: true,
  70736. configurable: true
  70737. });
  70738. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70739. get: function () {
  70740. return this._bloomWeight;
  70741. },
  70742. /**
  70743. * The strength of the bloom.
  70744. */
  70745. set: function (value) {
  70746. if (this._bloomWeight === value) {
  70747. return;
  70748. }
  70749. this._bloomWeight = value;
  70750. if (this._hdr && this.copyBack) {
  70751. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70752. }
  70753. },
  70754. enumerable: true,
  70755. configurable: true
  70756. });
  70757. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70758. get: function () {
  70759. return this._bloomScale;
  70760. },
  70761. /**
  70762. * The scale of the bloom, lower value will provide better performance.
  70763. */
  70764. set: function (value) {
  70765. if (this._bloomScale === value) {
  70766. return;
  70767. }
  70768. this._bloomScale = value;
  70769. this._buildPipeline();
  70770. },
  70771. enumerable: true,
  70772. configurable: true
  70773. });
  70774. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70775. get: function () {
  70776. return this._bloomEnabled;
  70777. },
  70778. /**
  70779. * Enable or disable the bloom from the pipeline
  70780. */
  70781. set: function (enabled) {
  70782. if (this._bloomEnabled === enabled) {
  70783. return;
  70784. }
  70785. this._bloomEnabled = enabled;
  70786. this._buildPipeline();
  70787. },
  70788. enumerable: true,
  70789. configurable: true
  70790. });
  70791. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70792. /**
  70793. * If the depth of field is enabled.
  70794. */
  70795. get: function () {
  70796. return this._depthOfFieldEnabled;
  70797. },
  70798. set: function (enabled) {
  70799. if (this._depthOfFieldEnabled === enabled) {
  70800. return;
  70801. }
  70802. this._depthOfFieldEnabled = enabled;
  70803. this._buildPipeline();
  70804. },
  70805. enumerable: true,
  70806. configurable: true
  70807. });
  70808. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70809. /**
  70810. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70811. */
  70812. get: function () {
  70813. return this._depthOfFieldBlurLevel;
  70814. },
  70815. set: function (value) {
  70816. if (this._depthOfFieldBlurLevel === value) {
  70817. return;
  70818. }
  70819. this._depthOfFieldBlurLevel = value;
  70820. // recreate dof and dispose old as this setting is not dynamic
  70821. var oldDof = this.depthOfField;
  70822. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70823. this.depthOfField.focalLength = oldDof.focalLength;
  70824. this.depthOfField.focusDistance = oldDof.focusDistance;
  70825. this.depthOfField.fStop = oldDof.fStop;
  70826. this.depthOfField.lensSize = oldDof.lensSize;
  70827. for (var i = 0; i < this._cameras.length; i++) {
  70828. oldDof.disposeEffects(this._cameras[i]);
  70829. }
  70830. this._buildPipeline();
  70831. },
  70832. enumerable: true,
  70833. configurable: true
  70834. });
  70835. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70836. get: function () {
  70837. return this._fxaaEnabled;
  70838. },
  70839. /**
  70840. * If the anti aliasing is enabled.
  70841. */
  70842. set: function (enabled) {
  70843. if (this._fxaaEnabled === enabled) {
  70844. return;
  70845. }
  70846. this._fxaaEnabled = enabled;
  70847. this._buildPipeline();
  70848. },
  70849. enumerable: true,
  70850. configurable: true
  70851. });
  70852. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70853. get: function () {
  70854. return this._msaaEnabled;
  70855. },
  70856. /**
  70857. * If the multisample anti-aliasing is enabled.
  70858. */
  70859. set: function (enabled) {
  70860. if (this._msaaEnabled === enabled) {
  70861. return;
  70862. }
  70863. this._msaaEnabled = enabled;
  70864. this._buildPipeline();
  70865. },
  70866. enumerable: true,
  70867. configurable: true
  70868. });
  70869. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70870. get: function () {
  70871. return this._imageProcessingEnabled;
  70872. },
  70873. /**
  70874. * If image processing is enabled.
  70875. */
  70876. set: function (enabled) {
  70877. if (this._imageProcessingEnabled === enabled) {
  70878. return;
  70879. }
  70880. this._imageProcessingEnabled = enabled;
  70881. this._buildPipeline();
  70882. },
  70883. enumerable: true,
  70884. configurable: true
  70885. });
  70886. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70887. get: function () {
  70888. return this._chromaticAberrationEnabled;
  70889. },
  70890. /**
  70891. * Enable or disable the chromaticAberration process from the pipeline
  70892. */
  70893. set: function (enabled) {
  70894. if (this._chromaticAberrationEnabled === enabled) {
  70895. return;
  70896. }
  70897. this._chromaticAberrationEnabled = enabled;
  70898. this._buildPipeline();
  70899. },
  70900. enumerable: true,
  70901. configurable: true
  70902. });
  70903. /**
  70904. * Force the compilation of the entire pipeline.
  70905. */
  70906. DefaultRenderingPipeline.prototype.prepare = function () {
  70907. var previousState = this._buildAllowed;
  70908. this._buildAllowed = true;
  70909. this._buildPipeline();
  70910. this._buildAllowed = previousState;
  70911. };
  70912. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70913. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70914. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70915. postProcess.autoClear = false;
  70916. }
  70917. else {
  70918. postProcess.autoClear = true;
  70919. }
  70920. if (!skipTextureSharing) {
  70921. if (this._prevPrevPostProcess) {
  70922. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70923. }
  70924. else {
  70925. postProcess.useOwnOutput();
  70926. }
  70927. if (this._prevPostProcess) {
  70928. this._prevPrevPostProcess = this._prevPostProcess;
  70929. }
  70930. this._prevPostProcess = postProcess;
  70931. }
  70932. };
  70933. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70934. var _this = this;
  70935. if (!this._buildAllowed) {
  70936. return;
  70937. }
  70938. var engine = this._scene.getEngine();
  70939. this._disposePostProcesses();
  70940. if (this._cameras !== null) {
  70941. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70942. // get back cameras to be used to reattach pipeline
  70943. this._cameras = this._originalCameras.slice();
  70944. }
  70945. this._reset();
  70946. this._prevPostProcess = null;
  70947. this._prevPrevPostProcess = null;
  70948. if (this.sharpenEnabled) {
  70949. if (!this.sharpen.isReady()) {
  70950. this.sharpen.updateEffect();
  70951. }
  70952. this.addEffect(this._sharpenEffect);
  70953. this._setAutoClearAndTextureSharing(this.sharpen);
  70954. }
  70955. if (this.depthOfFieldEnabled) {
  70956. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70957. this.depthOfField.depthTexture = depthTexture;
  70958. if (!this.depthOfField._isReady()) {
  70959. this.depthOfField._updateEffects();
  70960. }
  70961. this.addEffect(this.depthOfField);
  70962. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70963. }
  70964. if (this.bloomEnabled) {
  70965. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70966. this._setAutoClearAndTextureSharing(this.pass, true);
  70967. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70968. if (!this._hdr) {
  70969. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70970. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70971. this.highlights.autoClear = false;
  70972. this.highlights.alwaysForcePOT = true;
  70973. }
  70974. 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);
  70975. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70976. this.blurX.alwaysForcePOT = true;
  70977. this.blurX.autoClear = false;
  70978. this.blurX.onActivateObservable.add(function () {
  70979. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70980. _this.blurX.kernel = _this.bloomKernel * dw;
  70981. });
  70982. 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);
  70983. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70984. this.blurY.alwaysForcePOT = true;
  70985. this.blurY.autoClear = false;
  70986. this.blurY.onActivateObservable.add(function () {
  70987. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70988. _this.blurY.kernel = _this.bloomKernel * dh;
  70989. });
  70990. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70991. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70992. this.copyBack.alwaysForcePOT = true;
  70993. if (this._hdr) {
  70994. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70995. var w = this.bloomWeight;
  70996. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70997. }
  70998. else {
  70999. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  71000. }
  71001. this.copyBack.autoClear = false;
  71002. }
  71003. if (this._imageProcessingEnabled) {
  71004. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71005. if (this._hdr) {
  71006. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  71007. }
  71008. else {
  71009. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  71010. }
  71011. }
  71012. if (this._hdr && this.imageProcessing) {
  71013. this.finalMerge = this.imageProcessing;
  71014. }
  71015. else {
  71016. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71017. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  71018. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  71019. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  71020. }
  71021. if (this.bloomEnabled) {
  71022. if (this._hdr) {
  71023. this.copyBack.shareOutputWith(this.blurX);
  71024. if (this.imageProcessing) {
  71025. this.imageProcessing.shareOutputWith(this.pass);
  71026. this.imageProcessing.autoClear = false;
  71027. }
  71028. else {
  71029. this.finalMerge.shareOutputWith(this.pass);
  71030. }
  71031. }
  71032. else {
  71033. this.finalMerge.shareOutputWith(this.pass);
  71034. }
  71035. }
  71036. if (this.fxaaEnabled) {
  71037. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71038. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  71039. this._setAutoClearAndTextureSharing(this.fxaa);
  71040. }
  71041. if (this.chromaticAberrationEnabled) {
  71042. if (!this.chromaticAberration.isReady()) {
  71043. this.chromaticAberration.updateEffect();
  71044. }
  71045. this.addEffect(this._chromaticAberrationEffect);
  71046. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  71047. }
  71048. if (this._cameras !== null) {
  71049. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71050. }
  71051. if (this.msaaEnabled) {
  71052. if (!this._enableMSAAOnFirstPostProcess()) {
  71053. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  71054. }
  71055. }
  71056. };
  71057. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  71058. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  71059. for (var i = 0; i < this._cameras.length; i++) {
  71060. var camera = this._cameras[i];
  71061. if (this.pass) {
  71062. this.pass.dispose(camera);
  71063. }
  71064. if (this.highlights) {
  71065. this.highlights.dispose(camera);
  71066. }
  71067. if (this.blurX) {
  71068. this.blurX.dispose(camera);
  71069. }
  71070. if (this.blurY) {
  71071. this.blurY.dispose(camera);
  71072. }
  71073. if (this.copyBack) {
  71074. this.copyBack.dispose(camera);
  71075. }
  71076. if (this.imageProcessing) {
  71077. this.imageProcessing.dispose(camera);
  71078. }
  71079. if (this.fxaa) {
  71080. this.fxaa.dispose(camera);
  71081. }
  71082. if (this.finalMerge) {
  71083. this.finalMerge.dispose(camera);
  71084. }
  71085. // These are created in the constructor and should not be disposed on every pipeline change
  71086. if (disposeNonRecreated) {
  71087. if (this.sharpen) {
  71088. this.sharpen.dispose(camera);
  71089. }
  71090. if (this.depthOfField) {
  71091. this.depthOfField.disposeEffects(camera);
  71092. }
  71093. if (this.chromaticAberration) {
  71094. this.chromaticAberration.dispose(camera);
  71095. }
  71096. }
  71097. }
  71098. this.pass = null;
  71099. this.highlights = null;
  71100. this.blurX = null;
  71101. this.blurY = null;
  71102. this.copyBack = null;
  71103. this.imageProcessing = null;
  71104. this.fxaa = null;
  71105. this.finalMerge = null;
  71106. if (disposeNonRecreated) {
  71107. this.sharpen = null;
  71108. this.depthOfField = null;
  71109. this.chromaticAberration = null;
  71110. }
  71111. };
  71112. /**
  71113. * Dispose of the pipeline and stop all post processes
  71114. */
  71115. DefaultRenderingPipeline.prototype.dispose = function () {
  71116. this._disposePostProcesses(true);
  71117. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71118. _super.prototype.dispose.call(this);
  71119. };
  71120. /**
  71121. * Serialize the rendering pipeline (Used when exporting)
  71122. * @returns the serialized object
  71123. */
  71124. DefaultRenderingPipeline.prototype.serialize = function () {
  71125. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  71126. serializationObject.customType = "DefaultRenderingPipeline";
  71127. return serializationObject;
  71128. };
  71129. /**
  71130. * Parse the serialized pipeline
  71131. * @param source Source pipeline.
  71132. * @param scene The scene to load the pipeline to.
  71133. * @param rootUrl The URL of the serialized pipeline.
  71134. * @returns An instantiated pipeline from the serialized object.
  71135. */
  71136. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  71137. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  71138. };
  71139. __decorate([
  71140. BABYLON.serialize()
  71141. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  71142. __decorate([
  71143. BABYLON.serialize()
  71144. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  71145. __decorate([
  71146. BABYLON.serialize()
  71147. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  71148. __decorate([
  71149. BABYLON.serialize()
  71150. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  71151. __decorate([
  71152. BABYLON.serialize()
  71153. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  71154. __decorate([
  71155. BABYLON.serialize()
  71156. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  71157. __decorate([
  71158. BABYLON.serialize()
  71159. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  71160. __decorate([
  71161. BABYLON.serialize()
  71162. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  71163. __decorate([
  71164. BABYLON.serialize()
  71165. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  71166. __decorate([
  71167. BABYLON.serialize()
  71168. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  71169. __decorate([
  71170. BABYLON.serialize()
  71171. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  71172. __decorate([
  71173. BABYLON.serialize()
  71174. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  71175. __decorate([
  71176. BABYLON.serialize()
  71177. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  71178. return DefaultRenderingPipeline;
  71179. }(BABYLON.PostProcessRenderPipeline));
  71180. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  71181. })(BABYLON || (BABYLON = {}));
  71182. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  71183. "use strict";
  71184. var BABYLON;
  71185. (function (BABYLON) {
  71186. /**
  71187. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  71188. */
  71189. var GeometryBufferRenderer = /** @class */ (function () {
  71190. /**
  71191. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  71192. * @param scene The scene the buffer belongs to
  71193. * @param ratio How big is the buffer related to the main canvas.
  71194. */
  71195. function GeometryBufferRenderer(scene, ratio) {
  71196. if (ratio === void 0) { ratio = 1; }
  71197. this._enablePosition = false;
  71198. this._scene = scene;
  71199. this._ratio = ratio;
  71200. // Render target
  71201. this._createRenderTargets();
  71202. }
  71203. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  71204. /**
  71205. * Set the render list (meshes to be rendered) used in the G buffer.
  71206. */
  71207. set: function (meshes) {
  71208. this._multiRenderTarget.renderList = meshes;
  71209. },
  71210. enumerable: true,
  71211. configurable: true
  71212. });
  71213. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  71214. /**
  71215. * Gets wether or not G buffer are supported by the running hardware.
  71216. * This requires draw buffer supports
  71217. */
  71218. get: function () {
  71219. return this._multiRenderTarget.isSupported;
  71220. },
  71221. enumerable: true,
  71222. configurable: true
  71223. });
  71224. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  71225. /**
  71226. * Gets wether or not position are enabled for the G buffer.
  71227. */
  71228. get: function () {
  71229. return this._enablePosition;
  71230. },
  71231. /**
  71232. * Sets wether or not position are enabled for the G buffer.
  71233. */
  71234. set: function (enable) {
  71235. this._enablePosition = enable;
  71236. this.dispose();
  71237. this._createRenderTargets();
  71238. },
  71239. enumerable: true,
  71240. configurable: true
  71241. });
  71242. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  71243. /**
  71244. * Gets the scene associated with the buffer.
  71245. */
  71246. get: function () {
  71247. return this._scene;
  71248. },
  71249. enumerable: true,
  71250. configurable: true
  71251. });
  71252. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  71253. /**
  71254. * Gets the ratio used by the buffer during its creation.
  71255. * How big is the buffer related to the main canvas.
  71256. */
  71257. get: function () {
  71258. return this._ratio;
  71259. },
  71260. enumerable: true,
  71261. configurable: true
  71262. });
  71263. /**
  71264. * Checks wether everything is ready to render a submesh to the G buffer.
  71265. * @param subMesh the submesh to check readiness for
  71266. * @param useInstances is the mesh drawn using instance or not
  71267. * @returns true if ready otherwise false
  71268. */
  71269. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  71270. var material = subMesh.getMaterial();
  71271. if (material && material.disableDepthWrite) {
  71272. return false;
  71273. }
  71274. var defines = [];
  71275. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71276. var mesh = subMesh.getMesh();
  71277. // Alpha test
  71278. if (material && material.needAlphaTesting()) {
  71279. defines.push("#define ALPHATEST");
  71280. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71281. attribs.push(BABYLON.VertexBuffer.UVKind);
  71282. defines.push("#define UV1");
  71283. }
  71284. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71285. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71286. defines.push("#define UV2");
  71287. }
  71288. }
  71289. // Buffers
  71290. if (this._enablePosition) {
  71291. defines.push("#define POSITION");
  71292. }
  71293. // Bones
  71294. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71295. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71296. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71297. if (mesh.numBoneInfluencers > 4) {
  71298. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71299. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71300. }
  71301. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71302. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71303. }
  71304. else {
  71305. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71306. }
  71307. // Instances
  71308. if (useInstances) {
  71309. defines.push("#define INSTANCES");
  71310. attribs.push("world0");
  71311. attribs.push("world1");
  71312. attribs.push("world2");
  71313. attribs.push("world3");
  71314. }
  71315. // Get correct effect
  71316. var join = defines.join("\n");
  71317. if (this._cachedDefines !== join) {
  71318. this._cachedDefines = join;
  71319. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71320. }
  71321. return this._effect.isReady();
  71322. };
  71323. /**
  71324. * Gets the current underlying G Buffer.
  71325. * @returns the buffer
  71326. */
  71327. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71328. return this._multiRenderTarget;
  71329. };
  71330. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71331. /**
  71332. * Gets the number of samples used to render the buffer (anti aliasing).
  71333. */
  71334. get: function () {
  71335. return this._multiRenderTarget.samples;
  71336. },
  71337. /**
  71338. * Sets the number of samples used to render the buffer (anti aliasing).
  71339. */
  71340. set: function (value) {
  71341. this._multiRenderTarget.samples = value;
  71342. },
  71343. enumerable: true,
  71344. configurable: true
  71345. });
  71346. /**
  71347. * Disposes the renderer and frees up associated resources.
  71348. */
  71349. GeometryBufferRenderer.prototype.dispose = function () {
  71350. this.getGBuffer().dispose();
  71351. };
  71352. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71353. var _this = this;
  71354. var engine = this._scene.getEngine();
  71355. var count = this._enablePosition ? 3 : 2;
  71356. 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 });
  71357. if (!this.isSupported) {
  71358. return;
  71359. }
  71360. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71361. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71362. this._multiRenderTarget.refreshRate = 1;
  71363. this._multiRenderTarget.renderParticles = false;
  71364. this._multiRenderTarget.renderList = null;
  71365. // set default depth value to 1.0 (far away)
  71366. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71367. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71368. });
  71369. // Custom render function
  71370. var renderSubMesh = function (subMesh) {
  71371. var mesh = subMesh.getRenderingMesh();
  71372. var scene = _this._scene;
  71373. var engine = scene.getEngine();
  71374. var material = subMesh.getMaterial();
  71375. if (!material) {
  71376. return;
  71377. }
  71378. // Culling
  71379. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71380. // Managing instances
  71381. var batch = mesh._getInstancesRenderList(subMesh._id);
  71382. if (batch.mustReturn) {
  71383. return;
  71384. }
  71385. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71386. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71387. engine.enableEffect(_this._effect);
  71388. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71389. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71390. _this._effect.setMatrix("view", scene.getViewMatrix());
  71391. // Alpha test
  71392. if (material && material.needAlphaTesting()) {
  71393. var alphaTexture = material.getAlphaTestTexture();
  71394. if (alphaTexture) {
  71395. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71396. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71397. }
  71398. }
  71399. // Bones
  71400. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71401. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71402. }
  71403. // Draw
  71404. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71405. }
  71406. };
  71407. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71408. var index;
  71409. if (depthOnlySubMeshes.length) {
  71410. engine.setColorWrite(false);
  71411. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71412. renderSubMesh(depthOnlySubMeshes.data[index]);
  71413. }
  71414. engine.setColorWrite(true);
  71415. }
  71416. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71417. renderSubMesh(opaqueSubMeshes.data[index]);
  71418. }
  71419. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71420. renderSubMesh(alphaTestSubMeshes.data[index]);
  71421. }
  71422. };
  71423. };
  71424. return GeometryBufferRenderer;
  71425. }());
  71426. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71427. })(BABYLON || (BABYLON = {}));
  71428. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71429. "use strict";
  71430. var BABYLON;
  71431. (function (BABYLON) {
  71432. var RefractionPostProcess = /** @class */ (function (_super) {
  71433. __extends(RefractionPostProcess, _super);
  71434. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71435. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71436. _this.color = color;
  71437. _this.depth = depth;
  71438. _this.colorLevel = colorLevel;
  71439. _this._ownRefractionTexture = true;
  71440. _this.onActivateObservable.add(function (cam) {
  71441. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71442. });
  71443. _this.onApplyObservable.add(function (effect) {
  71444. effect.setColor3("baseColor", _this.color);
  71445. effect.setFloat("depth", _this.depth);
  71446. effect.setFloat("colorLevel", _this.colorLevel);
  71447. effect.setTexture("refractionSampler", _this._refTexture);
  71448. });
  71449. return _this;
  71450. }
  71451. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71452. /**
  71453. * Gets or sets the refraction texture
  71454. * Please note that you are responsible for disposing the texture if you set it manually
  71455. */
  71456. get: function () {
  71457. return this._refTexture;
  71458. },
  71459. set: function (value) {
  71460. if (this._refTexture && this._ownRefractionTexture) {
  71461. this._refTexture.dispose();
  71462. }
  71463. this._refTexture = value;
  71464. this._ownRefractionTexture = false;
  71465. },
  71466. enumerable: true,
  71467. configurable: true
  71468. });
  71469. // Methods
  71470. RefractionPostProcess.prototype.dispose = function (camera) {
  71471. if (this._refTexture && this._ownRefractionTexture) {
  71472. this._refTexture.dispose();
  71473. this._refTexture = null;
  71474. }
  71475. _super.prototype.dispose.call(this, camera);
  71476. };
  71477. return RefractionPostProcess;
  71478. }(BABYLON.PostProcess));
  71479. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71480. })(BABYLON || (BABYLON = {}));
  71481. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71482. "use strict";
  71483. var BABYLON;
  71484. (function (BABYLON) {
  71485. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71486. __extends(BlackAndWhitePostProcess, _super);
  71487. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71488. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71489. _this.degree = 1;
  71490. _this.onApplyObservable.add(function (effect) {
  71491. effect.setFloat("degree", _this.degree);
  71492. });
  71493. return _this;
  71494. }
  71495. return BlackAndWhitePostProcess;
  71496. }(BABYLON.PostProcess));
  71497. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71498. })(BABYLON || (BABYLON = {}));
  71499. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71500. "use strict";
  71501. var BABYLON;
  71502. (function (BABYLON) {
  71503. /**
  71504. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71505. * input texture to perform effects such as edge detection or sharpening
  71506. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71507. */
  71508. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71509. __extends(ConvolutionPostProcess, _super);
  71510. /**
  71511. * Creates a new instance of @see ConvolutionPostProcess
  71512. * @param name The name of the effect.
  71513. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71514. * @param options The required width/height ratio to downsize to before computing the render pass.
  71515. * @param camera The camera to apply the render pass to.
  71516. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71517. * @param engine The engine which the post process will be applied. (default: current engine)
  71518. * @param reusable If the post process can be reused on the same frame. (default: false)
  71519. * @param textureType Type of textures used when performing the post process. (default: 0)
  71520. */
  71521. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71522. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71523. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71524. _this.kernel = kernel;
  71525. _this.onApply = function (effect) {
  71526. effect.setFloat2("screenSize", _this.width, _this.height);
  71527. effect.setArray("kernel", _this.kernel);
  71528. };
  71529. return _this;
  71530. }
  71531. // Statics
  71532. /**
  71533. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71534. */
  71535. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71536. /**
  71537. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71538. */
  71539. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71540. /**
  71541. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71542. */
  71543. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71544. /**
  71545. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71546. */
  71547. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71548. /**
  71549. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71550. */
  71551. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71552. /**
  71553. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71554. */
  71555. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71556. return ConvolutionPostProcess;
  71557. }(BABYLON.PostProcess));
  71558. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71559. })(BABYLON || (BABYLON = {}));
  71560. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71561. "use strict";
  71562. var BABYLON;
  71563. (function (BABYLON) {
  71564. var FilterPostProcess = /** @class */ (function (_super) {
  71565. __extends(FilterPostProcess, _super);
  71566. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71567. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71568. _this.kernelMatrix = kernelMatrix;
  71569. _this.onApply = function (effect) {
  71570. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71571. };
  71572. return _this;
  71573. }
  71574. return FilterPostProcess;
  71575. }(BABYLON.PostProcess));
  71576. BABYLON.FilterPostProcess = FilterPostProcess;
  71577. })(BABYLON || (BABYLON = {}));
  71578. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71579. "use strict";
  71580. var BABYLON;
  71581. (function (BABYLON) {
  71582. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71583. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71584. __extends(VolumetricLightScatteringPostProcess, _super);
  71585. /**
  71586. * @constructor
  71587. * @param {string} name - The post-process name
  71588. * @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)
  71589. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71590. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71591. * @param {number} samples - The post-process quality, default 100
  71592. * @param {number} samplingMode - The post-process filtering mode
  71593. * @param {BABYLON.Engine} engine - The babylon engine
  71594. * @param {boolean} reusable - If the post-process is reusable
  71595. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71596. */
  71597. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71598. if (samples === void 0) { samples = 100; }
  71599. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71600. 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;
  71601. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71602. /**
  71603. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71604. * @type {Vector3}
  71605. */
  71606. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71607. /**
  71608. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71609. * @type {boolean}
  71610. */
  71611. _this.useCustomMeshPosition = false;
  71612. /**
  71613. * If the post-process should inverse the light scattering direction
  71614. * @type {boolean}
  71615. */
  71616. _this.invert = true;
  71617. /**
  71618. * Array containing the excluded meshes not rendered in the internal pass
  71619. */
  71620. _this.excludedMeshes = new Array();
  71621. /**
  71622. * Controls the overall intensity of the post-process
  71623. * @type {number}
  71624. */
  71625. _this.exposure = 0.3;
  71626. /**
  71627. * Dissipates each sample's contribution in range [0, 1]
  71628. * @type {number}
  71629. */
  71630. _this.decay = 0.96815;
  71631. /**
  71632. * Controls the overall intensity of each sample
  71633. * @type {number}
  71634. */
  71635. _this.weight = 0.58767;
  71636. /**
  71637. * Controls the density of each sample
  71638. * @type {number}
  71639. */
  71640. _this.density = 0.926;
  71641. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71642. engine = scene.getEngine();
  71643. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71644. // Configure mesh
  71645. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71646. // Configure
  71647. _this._createPass(scene, ratio.passRatio || ratio);
  71648. _this.onActivate = function (camera) {
  71649. if (!_this.isSupported) {
  71650. _this.dispose(camera);
  71651. }
  71652. _this.onActivate = null;
  71653. };
  71654. _this.onApplyObservable.add(function (effect) {
  71655. _this._updateMeshScreenCoordinates(scene);
  71656. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71657. effect.setFloat("exposure", _this.exposure);
  71658. effect.setFloat("decay", _this.decay);
  71659. effect.setFloat("weight", _this.weight);
  71660. effect.setFloat("density", _this.density);
  71661. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71662. });
  71663. return _this;
  71664. }
  71665. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71666. get: function () {
  71667. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71668. return false;
  71669. },
  71670. set: function (useDiffuseColor) {
  71671. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71672. },
  71673. enumerable: true,
  71674. configurable: true
  71675. });
  71676. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71677. return "VolumetricLightScatteringPostProcess";
  71678. };
  71679. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71680. var mesh = subMesh.getMesh();
  71681. // Render this.mesh as default
  71682. if (mesh === this.mesh && mesh.material) {
  71683. return mesh.material.isReady(mesh);
  71684. }
  71685. var defines = [];
  71686. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71687. var material = subMesh.getMaterial();
  71688. // Alpha test
  71689. if (material) {
  71690. if (material.needAlphaTesting()) {
  71691. defines.push("#define ALPHATEST");
  71692. }
  71693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71694. attribs.push(BABYLON.VertexBuffer.UVKind);
  71695. defines.push("#define UV1");
  71696. }
  71697. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71698. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71699. defines.push("#define UV2");
  71700. }
  71701. }
  71702. // Bones
  71703. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71704. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71705. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71706. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71707. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71708. }
  71709. else {
  71710. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71711. }
  71712. // Instances
  71713. if (useInstances) {
  71714. defines.push("#define INSTANCES");
  71715. attribs.push("world0");
  71716. attribs.push("world1");
  71717. attribs.push("world2");
  71718. attribs.push("world3");
  71719. }
  71720. // Get correct effect
  71721. var join = defines.join("\n");
  71722. if (this._cachedDefines !== join) {
  71723. this._cachedDefines = join;
  71724. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71725. }
  71726. return this._volumetricLightScatteringPass.isReady();
  71727. };
  71728. /**
  71729. * Sets the new light position for light scattering effect
  71730. * @param {BABYLON.Vector3} The new custom light position
  71731. */
  71732. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71733. this.customMeshPosition = position;
  71734. };
  71735. /**
  71736. * Returns the light position for light scattering effect
  71737. * @return {BABYLON.Vector3} The custom light position
  71738. */
  71739. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71740. return this.customMeshPosition;
  71741. };
  71742. /**
  71743. * Disposes the internal assets and detaches the post-process from the camera
  71744. */
  71745. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71746. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71747. if (rttIndex !== -1) {
  71748. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71749. }
  71750. this._volumetricLightScatteringRTT.dispose();
  71751. _super.prototype.dispose.call(this, camera);
  71752. };
  71753. /**
  71754. * Returns the render target texture used by the post-process
  71755. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71756. */
  71757. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71758. return this._volumetricLightScatteringRTT;
  71759. };
  71760. // Private methods
  71761. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71762. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71763. return true;
  71764. }
  71765. return false;
  71766. };
  71767. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71768. var _this = this;
  71769. var engine = scene.getEngine();
  71770. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71771. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71772. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71773. this._volumetricLightScatteringRTT.renderList = null;
  71774. this._volumetricLightScatteringRTT.renderParticles = false;
  71775. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71776. var camera = this.getCamera();
  71777. if (camera) {
  71778. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71779. }
  71780. else {
  71781. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71782. }
  71783. // Custom render function for submeshes
  71784. var renderSubMesh = function (subMesh) {
  71785. var mesh = subMesh.getRenderingMesh();
  71786. if (_this._meshExcluded(mesh)) {
  71787. return;
  71788. }
  71789. var material = subMesh.getMaterial();
  71790. if (!material) {
  71791. return;
  71792. }
  71793. var scene = mesh.getScene();
  71794. var engine = scene.getEngine();
  71795. // Culling
  71796. engine.setState(material.backFaceCulling);
  71797. // Managing instances
  71798. var batch = mesh._getInstancesRenderList(subMesh._id);
  71799. if (batch.mustReturn) {
  71800. return;
  71801. }
  71802. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71803. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71804. var effect = _this._volumetricLightScatteringPass;
  71805. if (mesh === _this.mesh) {
  71806. if (subMesh.effect) {
  71807. effect = subMesh.effect;
  71808. }
  71809. else {
  71810. effect = material.getEffect();
  71811. }
  71812. }
  71813. engine.enableEffect(effect);
  71814. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71815. if (mesh === _this.mesh) {
  71816. material.bind(mesh.getWorldMatrix(), mesh);
  71817. }
  71818. else {
  71819. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71820. // Alpha test
  71821. if (material && material.needAlphaTesting()) {
  71822. var alphaTexture = material.getAlphaTestTexture();
  71823. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71824. if (alphaTexture) {
  71825. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71826. }
  71827. }
  71828. // Bones
  71829. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71830. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71831. }
  71832. }
  71833. // Draw
  71834. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71835. }
  71836. };
  71837. // Render target texture callbacks
  71838. var savedSceneClearColor;
  71839. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71840. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71841. savedSceneClearColor = scene.clearColor;
  71842. scene.clearColor = sceneClearColor;
  71843. });
  71844. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71845. scene.clearColor = savedSceneClearColor;
  71846. });
  71847. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71848. var engine = scene.getEngine();
  71849. var index;
  71850. if (depthOnlySubMeshes.length) {
  71851. engine.setColorWrite(false);
  71852. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71853. renderSubMesh(depthOnlySubMeshes.data[index]);
  71854. }
  71855. engine.setColorWrite(true);
  71856. }
  71857. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71858. renderSubMesh(opaqueSubMeshes.data[index]);
  71859. }
  71860. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71861. renderSubMesh(alphaTestSubMeshes.data[index]);
  71862. }
  71863. if (transparentSubMeshes.length) {
  71864. // Sort sub meshes
  71865. for (index = 0; index < transparentSubMeshes.length; index++) {
  71866. var submesh = transparentSubMeshes.data[index];
  71867. var boundingInfo = submesh.getBoundingInfo();
  71868. if (boundingInfo && scene.activeCamera) {
  71869. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71870. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71871. }
  71872. }
  71873. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71874. sortedArray.sort(function (a, b) {
  71875. // Alpha index first
  71876. if (a._alphaIndex > b._alphaIndex) {
  71877. return 1;
  71878. }
  71879. if (a._alphaIndex < b._alphaIndex) {
  71880. return -1;
  71881. }
  71882. // Then distance to camera
  71883. if (a._distanceToCamera < b._distanceToCamera) {
  71884. return 1;
  71885. }
  71886. if (a._distanceToCamera > b._distanceToCamera) {
  71887. return -1;
  71888. }
  71889. return 0;
  71890. });
  71891. // Render sub meshes
  71892. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71893. for (index = 0; index < sortedArray.length; index++) {
  71894. renderSubMesh(sortedArray[index]);
  71895. }
  71896. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71897. }
  71898. };
  71899. };
  71900. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71901. var transform = scene.getTransformMatrix();
  71902. var meshPosition;
  71903. if (this.useCustomMeshPosition) {
  71904. meshPosition = this.customMeshPosition;
  71905. }
  71906. else if (this.attachedNode) {
  71907. meshPosition = this.attachedNode.position;
  71908. }
  71909. else {
  71910. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71911. }
  71912. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71913. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71914. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71915. if (this.invert)
  71916. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71917. };
  71918. // Static methods
  71919. /**
  71920. * Creates a default mesh for the Volumeric Light Scattering post-process
  71921. * @param {string} The mesh name
  71922. * @param {BABYLON.Scene} The scene where to create the mesh
  71923. * @return {BABYLON.Mesh} the default mesh
  71924. */
  71925. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71926. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71927. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71928. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71929. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71930. mesh.material = material;
  71931. return mesh;
  71932. };
  71933. __decorate([
  71934. BABYLON.serializeAsVector3()
  71935. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71936. __decorate([
  71937. BABYLON.serialize()
  71938. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71939. __decorate([
  71940. BABYLON.serialize()
  71941. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71942. __decorate([
  71943. BABYLON.serializeAsMeshReference()
  71944. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71945. __decorate([
  71946. BABYLON.serialize()
  71947. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71948. __decorate([
  71949. BABYLON.serialize()
  71950. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71951. __decorate([
  71952. BABYLON.serialize()
  71953. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71954. __decorate([
  71955. BABYLON.serialize()
  71956. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71957. __decorate([
  71958. BABYLON.serialize()
  71959. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71960. return VolumetricLightScatteringPostProcess;
  71961. }(BABYLON.PostProcess));
  71962. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71963. })(BABYLON || (BABYLON = {}));
  71964. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71965. "use strict";
  71966. //
  71967. // This post-process allows the modification of rendered colors by using
  71968. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71969. //
  71970. // The object needs to be provided an url to a texture containing the color
  71971. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71972. // Use an image editing software to tweak the LUT to match your needs.
  71973. //
  71974. // For an example of a color LUT, see here:
  71975. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71976. // For explanations on color grading, see here:
  71977. // http://udn.epicgames.com/Three/ColorGrading.html
  71978. //
  71979. var BABYLON;
  71980. (function (BABYLON) {
  71981. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71982. __extends(ColorCorrectionPostProcess, _super);
  71983. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71984. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71985. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71986. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71987. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71988. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71989. _this.onApply = function (effect) {
  71990. effect.setTexture("colorTable", _this._colorTableTexture);
  71991. };
  71992. return _this;
  71993. }
  71994. return ColorCorrectionPostProcess;
  71995. }(BABYLON.PostProcess));
  71996. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71997. })(BABYLON || (BABYLON = {}));
  71998. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71999. "use strict";
  72000. var BABYLON;
  72001. (function (BABYLON) {
  72002. var TonemappingOperator;
  72003. (function (TonemappingOperator) {
  72004. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  72005. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  72006. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  72007. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  72008. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  72009. ;
  72010. var TonemapPostProcess = /** @class */ (function (_super) {
  72011. __extends(TonemapPostProcess, _super);
  72012. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  72013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72014. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72015. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  72016. _this._operator = _operator;
  72017. _this.exposureAdjustment = exposureAdjustment;
  72018. var defines = "#define ";
  72019. if (_this._operator === TonemappingOperator.Hable)
  72020. defines += "HABLE_TONEMAPPING";
  72021. else if (_this._operator === TonemappingOperator.Reinhard)
  72022. defines += "REINHARD_TONEMAPPING";
  72023. else if (_this._operator === TonemappingOperator.HejiDawson)
  72024. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  72025. else if (_this._operator === TonemappingOperator.Photographic)
  72026. defines += "PHOTOGRAPHIC_TONEMAPPING";
  72027. //sadly a second call to create the effect.
  72028. _this.updateEffect(defines);
  72029. _this.onApply = function (effect) {
  72030. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  72031. };
  72032. return _this;
  72033. }
  72034. return TonemapPostProcess;
  72035. }(BABYLON.PostProcess));
  72036. BABYLON.TonemapPostProcess = TonemapPostProcess;
  72037. })(BABYLON || (BABYLON = {}));
  72038. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  72039. "use strict";
  72040. var BABYLON;
  72041. (function (BABYLON) {
  72042. var DisplayPassPostProcess = /** @class */ (function (_super) {
  72043. __extends(DisplayPassPostProcess, _super);
  72044. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  72045. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  72046. }
  72047. return DisplayPassPostProcess;
  72048. }(BABYLON.PostProcess));
  72049. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  72050. })(BABYLON || (BABYLON = {}));
  72051. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  72052. "use strict";
  72053. var BABYLON;
  72054. (function (BABYLON) {
  72055. var HighlightsPostProcess = /** @class */ (function (_super) {
  72056. __extends(HighlightsPostProcess, _super);
  72057. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72058. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72059. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72060. }
  72061. return HighlightsPostProcess;
  72062. }(BABYLON.PostProcess));
  72063. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  72064. })(BABYLON || (BABYLON = {}));
  72065. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  72066. "use strict";
  72067. var BABYLON;
  72068. (function (BABYLON) {
  72069. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  72070. __extends(ImageProcessingPostProcess, _super);
  72071. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  72072. if (camera === void 0) { camera = null; }
  72073. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72074. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  72075. _this._fromLinearSpace = true;
  72076. /**
  72077. * Defines cache preventing GC.
  72078. */
  72079. _this._defines = {
  72080. IMAGEPROCESSING: false,
  72081. VIGNETTE: false,
  72082. VIGNETTEBLENDMODEMULTIPLY: false,
  72083. VIGNETTEBLENDMODEOPAQUE: false,
  72084. TONEMAPPING: false,
  72085. CONTRAST: false,
  72086. COLORCURVES: false,
  72087. COLORGRADING: false,
  72088. COLORGRADING3D: false,
  72089. FROMLINEARSPACE: false,
  72090. SAMPLER3DGREENDEPTH: false,
  72091. SAMPLER3DBGRMAP: false,
  72092. IMAGEPROCESSINGPOSTPROCESS: false,
  72093. EXPOSURE: false,
  72094. GRAIN: false,
  72095. };
  72096. // Setup the configuration as forced by the constructor. This would then not force the
  72097. // scene materials output in linear space and let untouched the default forward pass.
  72098. if (imageProcessingConfiguration) {
  72099. imageProcessingConfiguration.applyByPostProcess = true;
  72100. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  72101. // This will cause the shader to be compiled
  72102. _this.fromLinearSpace = false;
  72103. }
  72104. else {
  72105. _this._attachImageProcessingConfiguration(null, true);
  72106. _this.imageProcessingConfiguration.applyByPostProcess = true;
  72107. }
  72108. _this.onApply = function (effect) {
  72109. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  72110. };
  72111. return _this;
  72112. }
  72113. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  72114. /**
  72115. * Gets the image processing configuration used either in this material.
  72116. */
  72117. get: function () {
  72118. return this._imageProcessingConfiguration;
  72119. },
  72120. /**
  72121. * Sets the Default image processing configuration used either in the this material.
  72122. *
  72123. * If sets to null, the scene one is in use.
  72124. */
  72125. set: function (value) {
  72126. this._attachImageProcessingConfiguration(value);
  72127. },
  72128. enumerable: true,
  72129. configurable: true
  72130. });
  72131. /**
  72132. * Attaches a new image processing configuration to the PBR Material.
  72133. * @param configuration
  72134. */
  72135. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  72136. var _this = this;
  72137. if (doNotBuild === void 0) { doNotBuild = false; }
  72138. if (configuration === this._imageProcessingConfiguration) {
  72139. return;
  72140. }
  72141. // Detaches observer.
  72142. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72143. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72144. }
  72145. // Pick the scene configuration if needed.
  72146. if (!configuration) {
  72147. var scene = null;
  72148. var engine = this.getEngine();
  72149. var camera = this.getCamera();
  72150. if (camera) {
  72151. scene = camera.getScene();
  72152. }
  72153. else if (engine && engine.scenes) {
  72154. var scenes = engine.scenes;
  72155. scene = scenes[scenes.length - 1];
  72156. }
  72157. else {
  72158. scene = BABYLON.Engine.LastCreatedScene;
  72159. }
  72160. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  72161. }
  72162. else {
  72163. this._imageProcessingConfiguration = configuration;
  72164. }
  72165. // Attaches observer.
  72166. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  72167. _this._updateParameters();
  72168. });
  72169. // Ensure the effect will be rebuilt.
  72170. if (!doNotBuild) {
  72171. this._updateParameters();
  72172. }
  72173. };
  72174. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  72175. /**
  72176. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72177. */
  72178. get: function () {
  72179. return this.imageProcessingConfiguration.colorCurves;
  72180. },
  72181. /**
  72182. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72183. */
  72184. set: function (value) {
  72185. this.imageProcessingConfiguration.colorCurves = value;
  72186. },
  72187. enumerable: true,
  72188. configurable: true
  72189. });
  72190. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  72191. /**
  72192. * Gets wether the color curves effect is enabled.
  72193. */
  72194. get: function () {
  72195. return this.imageProcessingConfiguration.colorCurvesEnabled;
  72196. },
  72197. /**
  72198. * Sets wether the color curves effect is enabled.
  72199. */
  72200. set: function (value) {
  72201. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  72202. },
  72203. enumerable: true,
  72204. configurable: true
  72205. });
  72206. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  72207. /**
  72208. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72209. */
  72210. get: function () {
  72211. return this.imageProcessingConfiguration.colorGradingTexture;
  72212. },
  72213. /**
  72214. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72215. */
  72216. set: function (value) {
  72217. this.imageProcessingConfiguration.colorGradingTexture = value;
  72218. },
  72219. enumerable: true,
  72220. configurable: true
  72221. });
  72222. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  72223. /**
  72224. * Gets wether the color grading effect is enabled.
  72225. */
  72226. get: function () {
  72227. return this.imageProcessingConfiguration.colorGradingEnabled;
  72228. },
  72229. /**
  72230. * Gets wether the color grading effect is enabled.
  72231. */
  72232. set: function (value) {
  72233. this.imageProcessingConfiguration.colorGradingEnabled = value;
  72234. },
  72235. enumerable: true,
  72236. configurable: true
  72237. });
  72238. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  72239. /**
  72240. * Gets exposure used in the effect.
  72241. */
  72242. get: function () {
  72243. return this.imageProcessingConfiguration.exposure;
  72244. },
  72245. /**
  72246. * Sets exposure used in the effect.
  72247. */
  72248. set: function (value) {
  72249. this.imageProcessingConfiguration.exposure = value;
  72250. },
  72251. enumerable: true,
  72252. configurable: true
  72253. });
  72254. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  72255. /**
  72256. * Gets wether tonemapping is enabled or not.
  72257. */
  72258. get: function () {
  72259. return this._imageProcessingConfiguration.toneMappingEnabled;
  72260. },
  72261. /**
  72262. * Sets wether tonemapping is enabled or not
  72263. */
  72264. set: function (value) {
  72265. this._imageProcessingConfiguration.toneMappingEnabled = value;
  72266. },
  72267. enumerable: true,
  72268. configurable: true
  72269. });
  72270. ;
  72271. ;
  72272. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  72273. /**
  72274. * Gets contrast used in the effect.
  72275. */
  72276. get: function () {
  72277. return this.imageProcessingConfiguration.contrast;
  72278. },
  72279. /**
  72280. * Sets contrast used in the effect.
  72281. */
  72282. set: function (value) {
  72283. this.imageProcessingConfiguration.contrast = value;
  72284. },
  72285. enumerable: true,
  72286. configurable: true
  72287. });
  72288. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  72289. /**
  72290. * Gets Vignette stretch size.
  72291. */
  72292. get: function () {
  72293. return this.imageProcessingConfiguration.vignetteStretch;
  72294. },
  72295. /**
  72296. * Sets Vignette stretch size.
  72297. */
  72298. set: function (value) {
  72299. this.imageProcessingConfiguration.vignetteStretch = value;
  72300. },
  72301. enumerable: true,
  72302. configurable: true
  72303. });
  72304. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  72305. /**
  72306. * Gets Vignette centre X Offset.
  72307. */
  72308. get: function () {
  72309. return this.imageProcessingConfiguration.vignetteCentreX;
  72310. },
  72311. /**
  72312. * Sets Vignette centre X Offset.
  72313. */
  72314. set: function (value) {
  72315. this.imageProcessingConfiguration.vignetteCentreX = value;
  72316. },
  72317. enumerable: true,
  72318. configurable: true
  72319. });
  72320. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72321. /**
  72322. * Gets Vignette centre Y Offset.
  72323. */
  72324. get: function () {
  72325. return this.imageProcessingConfiguration.vignetteCentreY;
  72326. },
  72327. /**
  72328. * Sets Vignette centre Y Offset.
  72329. */
  72330. set: function (value) {
  72331. this.imageProcessingConfiguration.vignetteCentreY = value;
  72332. },
  72333. enumerable: true,
  72334. configurable: true
  72335. });
  72336. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72337. /**
  72338. * Gets Vignette weight or intensity of the vignette effect.
  72339. */
  72340. get: function () {
  72341. return this.imageProcessingConfiguration.vignetteWeight;
  72342. },
  72343. /**
  72344. * Sets Vignette weight or intensity of the vignette effect.
  72345. */
  72346. set: function (value) {
  72347. this.imageProcessingConfiguration.vignetteWeight = value;
  72348. },
  72349. enumerable: true,
  72350. configurable: true
  72351. });
  72352. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72353. /**
  72354. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72355. * if vignetteEnabled is set to true.
  72356. */
  72357. get: function () {
  72358. return this.imageProcessingConfiguration.vignetteColor;
  72359. },
  72360. /**
  72361. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72362. * if vignetteEnabled is set to true.
  72363. */
  72364. set: function (value) {
  72365. this.imageProcessingConfiguration.vignetteColor = value;
  72366. },
  72367. enumerable: true,
  72368. configurable: true
  72369. });
  72370. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72371. /**
  72372. * Gets Camera field of view used by the Vignette effect.
  72373. */
  72374. get: function () {
  72375. return this.imageProcessingConfiguration.vignetteCameraFov;
  72376. },
  72377. /**
  72378. * Sets Camera field of view used by the Vignette effect.
  72379. */
  72380. set: function (value) {
  72381. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72382. },
  72383. enumerable: true,
  72384. configurable: true
  72385. });
  72386. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72387. /**
  72388. * Gets the vignette blend mode allowing different kind of effect.
  72389. */
  72390. get: function () {
  72391. return this.imageProcessingConfiguration.vignetteBlendMode;
  72392. },
  72393. /**
  72394. * Sets the vignette blend mode allowing different kind of effect.
  72395. */
  72396. set: function (value) {
  72397. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72398. },
  72399. enumerable: true,
  72400. configurable: true
  72401. });
  72402. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72403. /**
  72404. * Gets wether the vignette effect is enabled.
  72405. */
  72406. get: function () {
  72407. return this.imageProcessingConfiguration.vignetteEnabled;
  72408. },
  72409. /**
  72410. * Sets wether the vignette effect is enabled.
  72411. */
  72412. set: function (value) {
  72413. this.imageProcessingConfiguration.vignetteEnabled = value;
  72414. },
  72415. enumerable: true,
  72416. configurable: true
  72417. });
  72418. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  72419. /**
  72420. * Gets wether the grain effect is enabled.
  72421. */
  72422. get: function () {
  72423. return this.imageProcessingConfiguration.grainEnabled;
  72424. },
  72425. /**
  72426. * Sets wether the grain effect is enabled.
  72427. */
  72428. set: function (value) {
  72429. this.imageProcessingConfiguration.grainEnabled = value;
  72430. },
  72431. enumerable: true,
  72432. configurable: true
  72433. });
  72434. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  72435. /**
  72436. * Gets the grain effect's intensity.
  72437. */
  72438. get: function () {
  72439. return this.imageProcessingConfiguration.grainIntensity;
  72440. },
  72441. /**
  72442. * Sets the grain effect's intensity.
  72443. */
  72444. set: function (value) {
  72445. this.imageProcessingConfiguration.grainIntensity = value;
  72446. },
  72447. enumerable: true,
  72448. configurable: true
  72449. });
  72450. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  72451. /**
  72452. * Gets wether the grain effect is animated.
  72453. */
  72454. get: function () {
  72455. return this.imageProcessingConfiguration.grainAnimated;
  72456. },
  72457. /**
  72458. * Sets wether the grain effect is animated.
  72459. */
  72460. set: function (value) {
  72461. this.imageProcessingConfiguration.grainAnimated = value;
  72462. },
  72463. enumerable: true,
  72464. configurable: true
  72465. });
  72466. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72467. /**
  72468. * Gets wether the input of the processing is in Gamma or Linear Space.
  72469. */
  72470. get: function () {
  72471. return this._fromLinearSpace;
  72472. },
  72473. /**
  72474. * Sets wether the input of the processing is in Gamma or Linear Space.
  72475. */
  72476. set: function (value) {
  72477. if (this._fromLinearSpace === value) {
  72478. return;
  72479. }
  72480. this._fromLinearSpace = value;
  72481. this._updateParameters();
  72482. },
  72483. enumerable: true,
  72484. configurable: true
  72485. });
  72486. ImageProcessingPostProcess.prototype.getClassName = function () {
  72487. return "ImageProcessingPostProcess";
  72488. };
  72489. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72490. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72491. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72492. var defines = "";
  72493. for (var define in this._defines) {
  72494. if (this._defines[define]) {
  72495. defines += "#define " + define + ";\r\n";
  72496. }
  72497. }
  72498. var samplers = ["textureSampler"];
  72499. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72500. var uniforms = ["scale"];
  72501. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72502. this.updateEffect(defines, uniforms, samplers);
  72503. };
  72504. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72505. _super.prototype.dispose.call(this, camera);
  72506. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72507. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72508. }
  72509. this.imageProcessingConfiguration.applyByPostProcess = false;
  72510. };
  72511. __decorate([
  72512. BABYLON.serialize()
  72513. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72514. return ImageProcessingPostProcess;
  72515. }(BABYLON.PostProcess));
  72516. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72517. })(BABYLON || (BABYLON = {}));
  72518. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72519. "use strict";
  72520. var BABYLON;
  72521. (function (BABYLON) {
  72522. var Bone = /** @class */ (function (_super) {
  72523. __extends(Bone, _super);
  72524. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72525. if (parentBone === void 0) { parentBone = null; }
  72526. if (localMatrix === void 0) { localMatrix = null; }
  72527. if (restPose === void 0) { restPose = null; }
  72528. if (baseMatrix === void 0) { baseMatrix = null; }
  72529. if (index === void 0) { index = null; }
  72530. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72531. _this.name = name;
  72532. _this.children = new Array();
  72533. _this.animations = new Array();
  72534. // Set this value to map this bone to a different index in the transform matrices.
  72535. // Set this value to -1 to exclude the bone from the transform matrices.
  72536. _this._index = null;
  72537. _this._worldTransform = new BABYLON.Matrix();
  72538. _this._absoluteTransform = new BABYLON.Matrix();
  72539. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72540. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72541. _this._scaleVector = BABYLON.Vector3.One();
  72542. _this._negateScaleChildren = BABYLON.Vector3.One();
  72543. _this._scalingDeterminant = 1;
  72544. _this._skeleton = skeleton;
  72545. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72546. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72547. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72548. _this._index = index;
  72549. skeleton.bones.push(_this);
  72550. _this.setParent(parentBone, false);
  72551. _this._updateDifferenceMatrix();
  72552. return _this;
  72553. }
  72554. Object.defineProperty(Bone.prototype, "_matrix", {
  72555. get: function () {
  72556. return this._localMatrix;
  72557. },
  72558. set: function (val) {
  72559. if (this._localMatrix) {
  72560. this._localMatrix.copyFrom(val);
  72561. }
  72562. else {
  72563. this._localMatrix = val;
  72564. }
  72565. },
  72566. enumerable: true,
  72567. configurable: true
  72568. });
  72569. // Members
  72570. Bone.prototype.getSkeleton = function () {
  72571. return this._skeleton;
  72572. };
  72573. Bone.prototype.getParent = function () {
  72574. return this._parent;
  72575. };
  72576. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72577. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72578. if (this._parent === parent) {
  72579. return;
  72580. }
  72581. if (this._parent) {
  72582. var index = this._parent.children.indexOf(this);
  72583. if (index !== -1) {
  72584. this._parent.children.splice(index, 1);
  72585. }
  72586. }
  72587. this._parent = parent;
  72588. if (this._parent) {
  72589. this._parent.children.push(this);
  72590. }
  72591. if (updateDifferenceMatrix) {
  72592. this._updateDifferenceMatrix();
  72593. }
  72594. };
  72595. Bone.prototype.getLocalMatrix = function () {
  72596. return this._localMatrix;
  72597. };
  72598. Bone.prototype.getBaseMatrix = function () {
  72599. return this._baseMatrix;
  72600. };
  72601. Bone.prototype.getRestPose = function () {
  72602. return this._restPose;
  72603. };
  72604. Bone.prototype.returnToRest = function () {
  72605. this.updateMatrix(this._restPose.clone());
  72606. };
  72607. Bone.prototype.getWorldMatrix = function () {
  72608. return this._worldTransform;
  72609. };
  72610. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72611. return this._invertedAbsoluteTransform;
  72612. };
  72613. Bone.prototype.getAbsoluteTransform = function () {
  72614. return this._absoluteTransform;
  72615. };
  72616. Object.defineProperty(Bone.prototype, "position", {
  72617. // Properties (matches AbstractMesh properties)
  72618. get: function () {
  72619. return this.getPosition();
  72620. },
  72621. set: function (newPosition) {
  72622. this.setPosition(newPosition);
  72623. },
  72624. enumerable: true,
  72625. configurable: true
  72626. });
  72627. Object.defineProperty(Bone.prototype, "rotation", {
  72628. get: function () {
  72629. return this.getRotation();
  72630. },
  72631. set: function (newRotation) {
  72632. this.setRotation(newRotation);
  72633. },
  72634. enumerable: true,
  72635. configurable: true
  72636. });
  72637. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72638. get: function () {
  72639. return this.getRotationQuaternion();
  72640. },
  72641. set: function (newRotation) {
  72642. this.setRotationQuaternion(newRotation);
  72643. },
  72644. enumerable: true,
  72645. configurable: true
  72646. });
  72647. Object.defineProperty(Bone.prototype, "scaling", {
  72648. get: function () {
  72649. return this.getScale();
  72650. },
  72651. set: function (newScaling) {
  72652. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72653. },
  72654. enumerable: true,
  72655. configurable: true
  72656. });
  72657. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72658. /**
  72659. * Gets the animation properties override
  72660. */
  72661. get: function () {
  72662. return this._skeleton.animationPropertiesOverride;
  72663. },
  72664. enumerable: true,
  72665. configurable: true
  72666. });
  72667. // Methods
  72668. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72669. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72670. this._baseMatrix = matrix.clone();
  72671. this._localMatrix = matrix.clone();
  72672. this._skeleton._markAsDirty();
  72673. if (updateDifferenceMatrix) {
  72674. this._updateDifferenceMatrix();
  72675. }
  72676. };
  72677. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72678. if (!rootMatrix) {
  72679. rootMatrix = this._baseMatrix;
  72680. }
  72681. if (this._parent) {
  72682. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72683. }
  72684. else {
  72685. this._absoluteTransform.copyFrom(rootMatrix);
  72686. }
  72687. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72688. for (var index = 0; index < this.children.length; index++) {
  72689. this.children[index]._updateDifferenceMatrix();
  72690. }
  72691. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72692. };
  72693. Bone.prototype.markAsDirty = function () {
  72694. this._currentRenderId++;
  72695. this._skeleton._markAsDirty();
  72696. };
  72697. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72698. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72699. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72700. // all animation may be coming from a library skeleton, so may need to create animation
  72701. if (this.animations.length === 0) {
  72702. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72703. this.animations[0].setKeys([]);
  72704. }
  72705. // get animation info / verify there is such a range from the source bone
  72706. var sourceRange = source.animations[0].getRange(rangeName);
  72707. if (!sourceRange) {
  72708. return false;
  72709. }
  72710. var from = sourceRange.from;
  72711. var to = sourceRange.to;
  72712. var sourceKeys = source.animations[0].getKeys();
  72713. // rescaling prep
  72714. var sourceBoneLength = source.length;
  72715. var sourceParent = source.getParent();
  72716. var parent = this.getParent();
  72717. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72718. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72719. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72720. var destKeys = this.animations[0].getKeys();
  72721. // loop vars declaration
  72722. var orig;
  72723. var origTranslation;
  72724. var mat;
  72725. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72726. orig = sourceKeys[key];
  72727. if (orig.frame >= from && orig.frame <= to) {
  72728. if (rescaleAsRequired) {
  72729. mat = orig.value.clone();
  72730. // scale based on parent ratio, when bone has parent
  72731. if (parentScalingReqd) {
  72732. origTranslation = mat.getTranslation();
  72733. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72734. // scale based on skeleton dimension ratio when root bone, and value is passed
  72735. }
  72736. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72737. origTranslation = mat.getTranslation();
  72738. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72739. // use original when root bone, and no data for skelDimensionsRatio
  72740. }
  72741. else {
  72742. mat = orig.value;
  72743. }
  72744. }
  72745. else {
  72746. mat = orig.value;
  72747. }
  72748. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72749. }
  72750. }
  72751. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72752. return true;
  72753. };
  72754. /**
  72755. * Translate the bone in local or world space.
  72756. * @param vec The amount to translate the bone.
  72757. * @param space The space that the translation is in.
  72758. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72759. */
  72760. Bone.prototype.translate = function (vec, space, mesh) {
  72761. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72762. var lm = this.getLocalMatrix();
  72763. if (space == BABYLON.Space.LOCAL) {
  72764. lm.m[12] += vec.x;
  72765. lm.m[13] += vec.y;
  72766. lm.m[14] += vec.z;
  72767. }
  72768. else {
  72769. var wm = null;
  72770. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72771. if (mesh) {
  72772. wm = mesh.getWorldMatrix();
  72773. }
  72774. this._skeleton.computeAbsoluteTransforms();
  72775. var tmat = Bone._tmpMats[0];
  72776. var tvec = Bone._tmpVecs[0];
  72777. if (this._parent) {
  72778. if (mesh && wm) {
  72779. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72780. tmat.multiplyToRef(wm, tmat);
  72781. }
  72782. else {
  72783. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72784. }
  72785. }
  72786. tmat.m[12] = 0;
  72787. tmat.m[13] = 0;
  72788. tmat.m[14] = 0;
  72789. tmat.invert();
  72790. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72791. lm.m[12] += tvec.x;
  72792. lm.m[13] += tvec.y;
  72793. lm.m[14] += tvec.z;
  72794. }
  72795. this.markAsDirty();
  72796. };
  72797. /**
  72798. * Set the postion of the bone in local or world space.
  72799. * @param position The position to set the bone.
  72800. * @param space The space that the position is in.
  72801. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72802. */
  72803. Bone.prototype.setPosition = function (position, space, mesh) {
  72804. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72805. var lm = this.getLocalMatrix();
  72806. if (space == BABYLON.Space.LOCAL) {
  72807. lm.m[12] = position.x;
  72808. lm.m[13] = position.y;
  72809. lm.m[14] = position.z;
  72810. }
  72811. else {
  72812. var wm = null;
  72813. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72814. if (mesh) {
  72815. wm = mesh.getWorldMatrix();
  72816. }
  72817. this._skeleton.computeAbsoluteTransforms();
  72818. var tmat = Bone._tmpMats[0];
  72819. var vec = Bone._tmpVecs[0];
  72820. if (this._parent) {
  72821. if (mesh && wm) {
  72822. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72823. tmat.multiplyToRef(wm, tmat);
  72824. }
  72825. else {
  72826. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72827. }
  72828. }
  72829. tmat.invert();
  72830. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72831. lm.m[12] = vec.x;
  72832. lm.m[13] = vec.y;
  72833. lm.m[14] = vec.z;
  72834. }
  72835. this.markAsDirty();
  72836. };
  72837. /**
  72838. * Set the absolute postion of the bone (world space).
  72839. * @param position The position to set the bone.
  72840. * @param mesh The mesh that this bone is attached to.
  72841. */
  72842. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72843. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72844. };
  72845. /**
  72846. * Set the scale of the bone on the x, y and z axes.
  72847. * @param x The scale of the bone on the x axis.
  72848. * @param x The scale of the bone on the y axis.
  72849. * @param z The scale of the bone on the z axis.
  72850. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72851. */
  72852. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72853. if (scaleChildren === void 0) { scaleChildren = false; }
  72854. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72855. if (!scaleChildren) {
  72856. this._negateScaleChildren.x = 1 / x;
  72857. this._negateScaleChildren.y = 1 / y;
  72858. this._negateScaleChildren.z = 1 / z;
  72859. }
  72860. this._syncScaleVector();
  72861. }
  72862. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72863. };
  72864. /**
  72865. * Scale the bone on the x, y and z axes.
  72866. * @param x The amount to scale the bone on the x axis.
  72867. * @param x The amount to scale the bone on the y axis.
  72868. * @param z The amount to scale the bone on the z axis.
  72869. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72870. */
  72871. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72872. if (scaleChildren === void 0) { scaleChildren = false; }
  72873. var locMat = this.getLocalMatrix();
  72874. var origLocMat = Bone._tmpMats[0];
  72875. origLocMat.copyFrom(locMat);
  72876. var origLocMatInv = Bone._tmpMats[1];
  72877. origLocMatInv.copyFrom(origLocMat);
  72878. origLocMatInv.invert();
  72879. var scaleMat = Bone._tmpMats[2];
  72880. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72881. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72882. this._scaleVector.x *= x;
  72883. this._scaleVector.y *= y;
  72884. this._scaleVector.z *= z;
  72885. locMat.multiplyToRef(origLocMatInv, locMat);
  72886. locMat.multiplyToRef(scaleMat, locMat);
  72887. locMat.multiplyToRef(origLocMat, locMat);
  72888. var parent = this.getParent();
  72889. if (parent) {
  72890. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72891. }
  72892. else {
  72893. this.getAbsoluteTransform().copyFrom(locMat);
  72894. }
  72895. var len = this.children.length;
  72896. scaleMat.invert();
  72897. for (var i = 0; i < len; i++) {
  72898. var child = this.children[i];
  72899. var cm = child.getLocalMatrix();
  72900. cm.multiplyToRef(scaleMat, cm);
  72901. var lm = child.getLocalMatrix();
  72902. lm.m[12] *= x;
  72903. lm.m[13] *= y;
  72904. lm.m[14] *= z;
  72905. }
  72906. this.computeAbsoluteTransforms();
  72907. if (scaleChildren) {
  72908. for (var i = 0; i < len; i++) {
  72909. this.children[i].scale(x, y, z, scaleChildren);
  72910. }
  72911. }
  72912. this.markAsDirty();
  72913. };
  72914. /**
  72915. * Set the yaw, pitch, and roll of the bone in local or world space.
  72916. * @param yaw The rotation of the bone on the y axis.
  72917. * @param pitch The rotation of the bone on the x axis.
  72918. * @param roll The rotation of the bone on the z axis.
  72919. * @param space The space that the axes of rotation are in.
  72920. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72921. */
  72922. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72923. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72924. var rotMat = Bone._tmpMats[0];
  72925. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72926. var rotMatInv = Bone._tmpMats[1];
  72927. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72928. rotMatInv.multiplyToRef(rotMat, rotMat);
  72929. this._rotateWithMatrix(rotMat, space, mesh);
  72930. };
  72931. /**
  72932. * Rotate the bone on an axis in local or world space.
  72933. * @param axis The axis to rotate the bone on.
  72934. * @param amount The amount to rotate the bone.
  72935. * @param space The space that the axis is in.
  72936. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72937. */
  72938. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72939. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72940. var rmat = Bone._tmpMats[0];
  72941. rmat.m[12] = 0;
  72942. rmat.m[13] = 0;
  72943. rmat.m[14] = 0;
  72944. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72945. this._rotateWithMatrix(rmat, space, mesh);
  72946. };
  72947. /**
  72948. * Set the rotation of the bone to a particular axis angle in local or world space.
  72949. * @param axis The axis to rotate the bone on.
  72950. * @param angle The angle that the bone should be rotated to.
  72951. * @param space The space that the axis is in.
  72952. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72953. */
  72954. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72955. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72956. var rotMat = Bone._tmpMats[0];
  72957. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72958. var rotMatInv = Bone._tmpMats[1];
  72959. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72960. rotMatInv.multiplyToRef(rotMat, rotMat);
  72961. this._rotateWithMatrix(rotMat, space, mesh);
  72962. };
  72963. /**
  72964. * Set the euler rotation of the bone in local of world space.
  72965. * @param rotation The euler rotation that the bone should be set to.
  72966. * @param space The space that the rotation is in.
  72967. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72968. */
  72969. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72970. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72971. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72972. };
  72973. /**
  72974. * Set the quaternion rotation of the bone in local of world space.
  72975. * @param quat The quaternion rotation that the bone should be set to.
  72976. * @param space The space that the rotation is in.
  72977. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72978. */
  72979. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72980. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72981. var rotMatInv = Bone._tmpMats[0];
  72982. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72983. var rotMat = Bone._tmpMats[1];
  72984. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72985. rotMatInv.multiplyToRef(rotMat, rotMat);
  72986. this._rotateWithMatrix(rotMat, space, mesh);
  72987. };
  72988. /**
  72989. * Set the rotation matrix of the bone in local of world space.
  72990. * @param rotMat The rotation matrix that the bone should be set to.
  72991. * @param space The space that the rotation is in.
  72992. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72993. */
  72994. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72995. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72996. var rotMatInv = Bone._tmpMats[0];
  72997. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72998. var rotMat2 = Bone._tmpMats[1];
  72999. rotMat2.copyFrom(rotMat);
  73000. rotMatInv.multiplyToRef(rotMat, rotMat2);
  73001. this._rotateWithMatrix(rotMat2, space, mesh);
  73002. };
  73003. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  73004. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73005. var lmat = this.getLocalMatrix();
  73006. var lx = lmat.m[12];
  73007. var ly = lmat.m[13];
  73008. var lz = lmat.m[14];
  73009. var parent = this.getParent();
  73010. var parentScale = Bone._tmpMats[3];
  73011. var parentScaleInv = Bone._tmpMats[4];
  73012. if (parent) {
  73013. if (space == BABYLON.Space.WORLD) {
  73014. if (mesh) {
  73015. parentScale.copyFrom(mesh.getWorldMatrix());
  73016. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  73017. }
  73018. else {
  73019. parentScale.copyFrom(parent.getAbsoluteTransform());
  73020. }
  73021. }
  73022. else {
  73023. parentScale = parent._scaleMatrix;
  73024. }
  73025. parentScaleInv.copyFrom(parentScale);
  73026. parentScaleInv.invert();
  73027. lmat.multiplyToRef(parentScale, lmat);
  73028. lmat.multiplyToRef(rmat, lmat);
  73029. lmat.multiplyToRef(parentScaleInv, lmat);
  73030. }
  73031. else {
  73032. if (space == BABYLON.Space.WORLD && mesh) {
  73033. parentScale.copyFrom(mesh.getWorldMatrix());
  73034. parentScaleInv.copyFrom(parentScale);
  73035. parentScaleInv.invert();
  73036. lmat.multiplyToRef(parentScale, lmat);
  73037. lmat.multiplyToRef(rmat, lmat);
  73038. lmat.multiplyToRef(parentScaleInv, lmat);
  73039. }
  73040. else {
  73041. lmat.multiplyToRef(rmat, lmat);
  73042. }
  73043. }
  73044. lmat.m[12] = lx;
  73045. lmat.m[13] = ly;
  73046. lmat.m[14] = lz;
  73047. this.computeAbsoluteTransforms();
  73048. this.markAsDirty();
  73049. };
  73050. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  73051. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73052. if (space == BABYLON.Space.WORLD) {
  73053. var scaleMatrix = Bone._tmpMats[2];
  73054. scaleMatrix.copyFrom(this._scaleMatrix);
  73055. rotMatInv.copyFrom(this.getAbsoluteTransform());
  73056. if (mesh) {
  73057. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  73058. var meshScale = Bone._tmpMats[3];
  73059. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  73060. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  73061. }
  73062. rotMatInv.invert();
  73063. scaleMatrix.m[0] *= this._scalingDeterminant;
  73064. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73065. }
  73066. else {
  73067. rotMatInv.copyFrom(this.getLocalMatrix());
  73068. rotMatInv.invert();
  73069. var scaleMatrix = Bone._tmpMats[2];
  73070. scaleMatrix.copyFrom(this._scaleMatrix);
  73071. if (this._parent) {
  73072. var pscaleMatrix = Bone._tmpMats[3];
  73073. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  73074. pscaleMatrix.invert();
  73075. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  73076. }
  73077. else {
  73078. scaleMatrix.m[0] *= this._scalingDeterminant;
  73079. }
  73080. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73081. }
  73082. };
  73083. /**
  73084. * Get the scale of the bone
  73085. * @returns the scale of the bone
  73086. */
  73087. Bone.prototype.getScale = function () {
  73088. return this._scaleVector.clone();
  73089. };
  73090. /**
  73091. * Copy the scale of the bone to a vector3.
  73092. * @param result The vector3 to copy the scale to
  73093. */
  73094. Bone.prototype.getScaleToRef = function (result) {
  73095. result.copyFrom(this._scaleVector);
  73096. };
  73097. /**
  73098. * Get the position of the bone in local or world space.
  73099. * @param space The space that the returned position is in.
  73100. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73101. * @returns The position of the bone
  73102. */
  73103. Bone.prototype.getPosition = function (space, mesh) {
  73104. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73105. if (mesh === void 0) { mesh = null; }
  73106. var pos = BABYLON.Vector3.Zero();
  73107. this.getPositionToRef(space, mesh, pos);
  73108. return pos;
  73109. };
  73110. /**
  73111. * Copy the position of the bone to a vector3 in local or world space.
  73112. * @param space The space that the returned position is in.
  73113. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73114. * @param result The vector3 to copy the position to.
  73115. */
  73116. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  73117. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73118. if (space == BABYLON.Space.LOCAL) {
  73119. var lm = this.getLocalMatrix();
  73120. result.x = lm.m[12];
  73121. result.y = lm.m[13];
  73122. result.z = lm.m[14];
  73123. }
  73124. else {
  73125. var wm = null;
  73126. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73127. if (mesh) {
  73128. wm = mesh.getWorldMatrix();
  73129. }
  73130. this._skeleton.computeAbsoluteTransforms();
  73131. var tmat = Bone._tmpMats[0];
  73132. if (mesh && wm) {
  73133. tmat.copyFrom(this.getAbsoluteTransform());
  73134. tmat.multiplyToRef(wm, tmat);
  73135. }
  73136. else {
  73137. tmat = this.getAbsoluteTransform();
  73138. }
  73139. result.x = tmat.m[12];
  73140. result.y = tmat.m[13];
  73141. result.z = tmat.m[14];
  73142. }
  73143. };
  73144. /**
  73145. * Get the absolute position of the bone (world space).
  73146. * @param mesh The mesh that this bone is attached to.
  73147. * @returns The absolute position of the bone
  73148. */
  73149. Bone.prototype.getAbsolutePosition = function (mesh) {
  73150. if (mesh === void 0) { mesh = null; }
  73151. var pos = BABYLON.Vector3.Zero();
  73152. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  73153. return pos;
  73154. };
  73155. /**
  73156. * Copy the absolute position of the bone (world space) to the result param.
  73157. * @param mesh The mesh that this bone is attached to.
  73158. * @param result The vector3 to copy the absolute position to.
  73159. */
  73160. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  73161. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  73162. };
  73163. /**
  73164. * Compute the absolute transforms of this bone and its children.
  73165. */
  73166. Bone.prototype.computeAbsoluteTransforms = function () {
  73167. if (this._parent) {
  73168. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  73169. }
  73170. else {
  73171. this._absoluteTransform.copyFrom(this._localMatrix);
  73172. var poseMatrix = this._skeleton.getPoseMatrix();
  73173. if (poseMatrix) {
  73174. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  73175. }
  73176. }
  73177. var children = this.children;
  73178. var len = children.length;
  73179. for (var i = 0; i < len; i++) {
  73180. children[i].computeAbsoluteTransforms();
  73181. }
  73182. };
  73183. Bone.prototype._syncScaleVector = function () {
  73184. var lm = this.getLocalMatrix();
  73185. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  73186. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  73187. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  73188. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  73189. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  73190. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  73191. this._scaleVector.x = xs * Math.sqrt(xsq);
  73192. this._scaleVector.y = ys * Math.sqrt(ysq);
  73193. this._scaleVector.z = zs * Math.sqrt(zsq);
  73194. if (this._parent) {
  73195. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  73196. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  73197. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  73198. }
  73199. 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);
  73200. };
  73201. /**
  73202. * Get the world direction from an axis that is in the local space of the bone.
  73203. * @param localAxis The local direction that is used to compute the world direction.
  73204. * @param mesh The mesh that this bone is attached to.
  73205. * @returns The world direction
  73206. */
  73207. Bone.prototype.getDirection = function (localAxis, mesh) {
  73208. if (mesh === void 0) { mesh = null; }
  73209. var result = BABYLON.Vector3.Zero();
  73210. this.getDirectionToRef(localAxis, mesh, result);
  73211. return result;
  73212. };
  73213. /**
  73214. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  73215. * @param localAxis The local direction that is used to compute the world direction.
  73216. * @param mesh The mesh that this bone is attached to.
  73217. * @param result The vector3 that the world direction will be copied to.
  73218. */
  73219. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  73220. if (mesh === void 0) { mesh = null; }
  73221. var wm = null;
  73222. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73223. if (mesh) {
  73224. wm = mesh.getWorldMatrix();
  73225. }
  73226. this._skeleton.computeAbsoluteTransforms();
  73227. var mat = Bone._tmpMats[0];
  73228. mat.copyFrom(this.getAbsoluteTransform());
  73229. if (mesh && wm) {
  73230. mat.multiplyToRef(wm, mat);
  73231. }
  73232. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  73233. result.normalize();
  73234. };
  73235. /**
  73236. * Get the euler rotation of the bone in local or world space.
  73237. * @param space The space that the rotation should be in.
  73238. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73239. * @returns The euler rotation
  73240. */
  73241. Bone.prototype.getRotation = function (space, mesh) {
  73242. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73243. if (mesh === void 0) { mesh = null; }
  73244. var result = BABYLON.Vector3.Zero();
  73245. this.getRotationToRef(space, mesh, result);
  73246. return result;
  73247. };
  73248. /**
  73249. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  73250. * @param space The space that the rotation should be in.
  73251. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73252. * @param result The vector3 that the rotation should be copied to.
  73253. */
  73254. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  73255. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73256. if (mesh === void 0) { mesh = null; }
  73257. var quat = Bone._tmpQuat;
  73258. this.getRotationQuaternionToRef(space, mesh, quat);
  73259. quat.toEulerAnglesToRef(result);
  73260. };
  73261. /**
  73262. * Get the quaternion rotation of the bone in either local or world space.
  73263. * @param space The space that the rotation should be in.
  73264. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73265. * @returns The quaternion rotation
  73266. */
  73267. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  73268. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73269. if (mesh === void 0) { mesh = null; }
  73270. var result = BABYLON.Quaternion.Identity();
  73271. this.getRotationQuaternionToRef(space, mesh, result);
  73272. return result;
  73273. };
  73274. /**
  73275. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  73276. * @param space The space that the rotation should be in.
  73277. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73278. * @param result The quaternion that the rotation should be copied to.
  73279. */
  73280. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  73281. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73282. if (mesh === void 0) { mesh = null; }
  73283. if (space == BABYLON.Space.LOCAL) {
  73284. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73285. }
  73286. else {
  73287. var mat = Bone._tmpMats[0];
  73288. var amat = this.getAbsoluteTransform();
  73289. if (mesh) {
  73290. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73291. }
  73292. else {
  73293. mat.copyFrom(amat);
  73294. }
  73295. mat.m[0] *= this._scalingDeterminant;
  73296. mat.m[1] *= this._scalingDeterminant;
  73297. mat.m[2] *= this._scalingDeterminant;
  73298. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73299. }
  73300. };
  73301. /**
  73302. * Get the rotation matrix of the bone in local or world space.
  73303. * @param space The space that the rotation should be in.
  73304. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73305. * @returns The rotation matrix
  73306. */
  73307. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73308. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73309. var result = BABYLON.Matrix.Identity();
  73310. this.getRotationMatrixToRef(space, mesh, result);
  73311. return result;
  73312. };
  73313. /**
  73314. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73315. * @param space The space that the rotation should be in.
  73316. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73317. * @param result The quaternion that the rotation should be copied to.
  73318. */
  73319. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73320. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73321. if (space == BABYLON.Space.LOCAL) {
  73322. this.getLocalMatrix().getRotationMatrixToRef(result);
  73323. }
  73324. else {
  73325. var mat = Bone._tmpMats[0];
  73326. var amat = this.getAbsoluteTransform();
  73327. if (mesh) {
  73328. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73329. }
  73330. else {
  73331. mat.copyFrom(amat);
  73332. }
  73333. mat.m[0] *= this._scalingDeterminant;
  73334. mat.m[1] *= this._scalingDeterminant;
  73335. mat.m[2] *= this._scalingDeterminant;
  73336. mat.getRotationMatrixToRef(result);
  73337. }
  73338. };
  73339. /**
  73340. * Get the world position of a point that is in the local space of the bone.
  73341. * @param position The local position
  73342. * @param mesh The mesh that this bone is attached to.
  73343. * @returns The world position
  73344. */
  73345. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73346. if (mesh === void 0) { mesh = null; }
  73347. var result = BABYLON.Vector3.Zero();
  73348. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73349. return result;
  73350. };
  73351. /**
  73352. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73353. * @param position The local position
  73354. * @param mesh The mesh that this bone is attached to.
  73355. * @param result The vector3 that the world position should be copied to.
  73356. */
  73357. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73358. if (mesh === void 0) { mesh = null; }
  73359. var wm = null;
  73360. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73361. if (mesh) {
  73362. wm = mesh.getWorldMatrix();
  73363. }
  73364. this._skeleton.computeAbsoluteTransforms();
  73365. var tmat = Bone._tmpMats[0];
  73366. if (mesh && wm) {
  73367. tmat.copyFrom(this.getAbsoluteTransform());
  73368. tmat.multiplyToRef(wm, tmat);
  73369. }
  73370. else {
  73371. tmat = this.getAbsoluteTransform();
  73372. }
  73373. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73374. };
  73375. /**
  73376. * Get the local position of a point that is in world space.
  73377. * @param position The world position
  73378. * @param mesh The mesh that this bone is attached to.
  73379. * @returns The local position
  73380. */
  73381. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73382. if (mesh === void 0) { mesh = null; }
  73383. var result = BABYLON.Vector3.Zero();
  73384. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73385. return result;
  73386. };
  73387. /**
  73388. * Get the local position of a point that is in world space and copy it to the result param.
  73389. * @param position The world position
  73390. * @param mesh The mesh that this bone is attached to.
  73391. * @param result The vector3 that the local position should be copied to.
  73392. */
  73393. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73394. if (mesh === void 0) { mesh = null; }
  73395. var wm = null;
  73396. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73397. if (mesh) {
  73398. wm = mesh.getWorldMatrix();
  73399. }
  73400. this._skeleton.computeAbsoluteTransforms();
  73401. var tmat = Bone._tmpMats[0];
  73402. tmat.copyFrom(this.getAbsoluteTransform());
  73403. if (mesh && wm) {
  73404. tmat.multiplyToRef(wm, tmat);
  73405. }
  73406. tmat.invert();
  73407. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73408. };
  73409. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73410. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73411. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73412. return Bone;
  73413. }(BABYLON.Node));
  73414. BABYLON.Bone = Bone;
  73415. })(BABYLON || (BABYLON = {}));
  73416. //# sourceMappingURL=babylon.bone.js.map
  73417. "use strict";
  73418. var BABYLON;
  73419. (function (BABYLON) {
  73420. var BoneIKController = /** @class */ (function () {
  73421. function BoneIKController(mesh, bone, options) {
  73422. this.targetPosition = BABYLON.Vector3.Zero();
  73423. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73424. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73425. this.poleAngle = 0;
  73426. this.slerpAmount = 1;
  73427. this._bone1Quat = BABYLON.Quaternion.Identity();
  73428. this._bone1Mat = BABYLON.Matrix.Identity();
  73429. this._bone2Ang = Math.PI;
  73430. this._maxAngle = Math.PI;
  73431. this._rightHandedSystem = false;
  73432. this._bendAxis = BABYLON.Vector3.Right();
  73433. this._slerping = false;
  73434. this._adjustRoll = 0;
  73435. this._bone2 = bone;
  73436. this._bone1 = bone.getParent();
  73437. if (!this._bone1) {
  73438. return;
  73439. }
  73440. this.mesh = mesh;
  73441. var bonePos = bone.getPosition();
  73442. if (bone.getAbsoluteTransform().determinant() > 0) {
  73443. this._rightHandedSystem = true;
  73444. this._bendAxis.x = 0;
  73445. this._bendAxis.y = 0;
  73446. this._bendAxis.z = -1;
  73447. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73448. this._adjustRoll = Math.PI * .5;
  73449. this._bendAxis.z = 1;
  73450. }
  73451. }
  73452. if (this._bone1.length) {
  73453. var boneScale1 = this._bone1.getScale();
  73454. var boneScale2 = this._bone2.getScale();
  73455. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73456. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73457. }
  73458. else if (this._bone1.children[0]) {
  73459. mesh.computeWorldMatrix(true);
  73460. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73461. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73462. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73463. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73464. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73465. }
  73466. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73467. this.maxAngle = Math.PI;
  73468. if (options) {
  73469. if (options.targetMesh) {
  73470. this.targetMesh = options.targetMesh;
  73471. this.targetMesh.computeWorldMatrix(true);
  73472. }
  73473. if (options.poleTargetMesh) {
  73474. this.poleTargetMesh = options.poleTargetMesh;
  73475. this.poleTargetMesh.computeWorldMatrix(true);
  73476. }
  73477. else if (options.poleTargetBone) {
  73478. this.poleTargetBone = options.poleTargetBone;
  73479. }
  73480. else if (this._bone1.getParent()) {
  73481. this.poleTargetBone = this._bone1.getParent();
  73482. }
  73483. if (options.poleTargetLocalOffset) {
  73484. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73485. }
  73486. if (options.poleAngle) {
  73487. this.poleAngle = options.poleAngle;
  73488. }
  73489. if (options.bendAxis) {
  73490. this._bendAxis.copyFrom(options.bendAxis);
  73491. }
  73492. if (options.maxAngle) {
  73493. this.maxAngle = options.maxAngle;
  73494. }
  73495. if (options.slerpAmount) {
  73496. this.slerpAmount = options.slerpAmount;
  73497. }
  73498. }
  73499. }
  73500. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73501. get: function () {
  73502. return this._maxAngle;
  73503. },
  73504. set: function (value) {
  73505. this._setMaxAngle(value);
  73506. },
  73507. enumerable: true,
  73508. configurable: true
  73509. });
  73510. BoneIKController.prototype._setMaxAngle = function (ang) {
  73511. if (ang < 0) {
  73512. ang = 0;
  73513. }
  73514. if (ang > Math.PI || ang == undefined) {
  73515. ang = Math.PI;
  73516. }
  73517. this._maxAngle = ang;
  73518. var a = this._bone1Length;
  73519. var b = this._bone2Length;
  73520. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73521. };
  73522. BoneIKController.prototype.update = function () {
  73523. var bone1 = this._bone1;
  73524. if (!bone1) {
  73525. return;
  73526. }
  73527. var target = this.targetPosition;
  73528. var poleTarget = this.poleTargetPosition;
  73529. var mat1 = BoneIKController._tmpMats[0];
  73530. var mat2 = BoneIKController._tmpMats[1];
  73531. if (this.targetMesh) {
  73532. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73533. }
  73534. if (this.poleTargetBone) {
  73535. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73536. }
  73537. else if (this.poleTargetMesh) {
  73538. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73539. }
  73540. var bonePos = BoneIKController._tmpVecs[0];
  73541. var zaxis = BoneIKController._tmpVecs[1];
  73542. var xaxis = BoneIKController._tmpVecs[2];
  73543. var yaxis = BoneIKController._tmpVecs[3];
  73544. var upAxis = BoneIKController._tmpVecs[4];
  73545. var _tmpQuat = BoneIKController._tmpQuat;
  73546. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73547. poleTarget.subtractToRef(bonePos, upAxis);
  73548. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73549. upAxis.y = 1;
  73550. }
  73551. else {
  73552. upAxis.normalize();
  73553. }
  73554. target.subtractToRef(bonePos, yaxis);
  73555. yaxis.normalize();
  73556. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73557. zaxis.normalize();
  73558. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73559. xaxis.normalize();
  73560. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73561. var a = this._bone1Length;
  73562. var b = this._bone2Length;
  73563. var c = BABYLON.Vector3.Distance(bonePos, target);
  73564. if (this._maxReach > 0) {
  73565. c = Math.min(this._maxReach, c);
  73566. }
  73567. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73568. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73569. if (acosa > 1) {
  73570. acosa = 1;
  73571. }
  73572. if (acosb > 1) {
  73573. acosb = 1;
  73574. }
  73575. if (acosa < -1) {
  73576. acosa = -1;
  73577. }
  73578. if (acosb < -1) {
  73579. acosb = -1;
  73580. }
  73581. var angA = Math.acos(acosa);
  73582. var angB = Math.acos(acosb);
  73583. var angC = -angA - angB;
  73584. if (this._rightHandedSystem) {
  73585. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73586. mat2.multiplyToRef(mat1, mat1);
  73587. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73588. mat2.multiplyToRef(mat1, mat1);
  73589. }
  73590. else {
  73591. var _tmpVec = BoneIKController._tmpVecs[5];
  73592. _tmpVec.copyFrom(this._bendAxis);
  73593. _tmpVec.x *= -1;
  73594. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73595. mat2.multiplyToRef(mat1, mat1);
  73596. }
  73597. if (this.poleAngle) {
  73598. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73599. mat1.multiplyToRef(mat2, mat1);
  73600. }
  73601. if (this._bone1) {
  73602. if (this.slerpAmount < 1) {
  73603. if (!this._slerping) {
  73604. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73605. }
  73606. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73607. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73608. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73609. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73610. this._slerping = true;
  73611. }
  73612. else {
  73613. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73614. this._bone1Mat.copyFrom(mat1);
  73615. this._slerping = false;
  73616. }
  73617. }
  73618. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73619. this._bone2Ang = angC;
  73620. };
  73621. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73622. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73623. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73624. return BoneIKController;
  73625. }());
  73626. BABYLON.BoneIKController = BoneIKController;
  73627. })(BABYLON || (BABYLON = {}));
  73628. //# sourceMappingURL=babylon.boneIKController.js.map
  73629. "use strict";
  73630. var BABYLON;
  73631. (function (BABYLON) {
  73632. var BoneLookController = /** @class */ (function () {
  73633. /**
  73634. * Create a BoneLookController
  73635. * @param mesh the mesh that the bone belongs to
  73636. * @param bone the bone that will be looking to the target
  73637. * @param target the target Vector3 to look at
  73638. * @param settings optional settings:
  73639. * - maxYaw: the maximum angle the bone will yaw to
  73640. * - minYaw: the minimum angle the bone will yaw to
  73641. * - maxPitch: the maximum angle the bone will pitch to
  73642. * - minPitch: the minimum angle the bone will yaw to
  73643. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73644. * - upAxis: the up axis of the coordinate system
  73645. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73646. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73647. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73648. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73649. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73650. * - adjustRoll: used to make an adjustment to the roll of the bone
  73651. **/
  73652. function BoneLookController(mesh, bone, target, options) {
  73653. /**
  73654. * The up axis of the coordinate system that is used when the bone is rotated.
  73655. */
  73656. this.upAxis = BABYLON.Vector3.Up();
  73657. /**
  73658. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73659. */
  73660. this.upAxisSpace = BABYLON.Space.LOCAL;
  73661. /**
  73662. * Used to make an adjustment to the yaw of the bone.
  73663. */
  73664. this.adjustYaw = 0;
  73665. /**
  73666. * Used to make an adjustment to the pitch of the bone.
  73667. */
  73668. this.adjustPitch = 0;
  73669. /**
  73670. * Used to make an adjustment to the roll of the bone.
  73671. */
  73672. this.adjustRoll = 0;
  73673. /**
  73674. * 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).
  73675. */
  73676. this.slerpAmount = 1;
  73677. this._boneQuat = BABYLON.Quaternion.Identity();
  73678. this._slerping = false;
  73679. this._firstFrameSkipped = false;
  73680. this._fowardAxis = BABYLON.Vector3.Forward();
  73681. this.mesh = mesh;
  73682. this.bone = bone;
  73683. this.target = target;
  73684. if (options) {
  73685. if (options.adjustYaw) {
  73686. this.adjustYaw = options.adjustYaw;
  73687. }
  73688. if (options.adjustPitch) {
  73689. this.adjustPitch = options.adjustPitch;
  73690. }
  73691. if (options.adjustRoll) {
  73692. this.adjustRoll = options.adjustRoll;
  73693. }
  73694. if (options.maxYaw != null) {
  73695. this.maxYaw = options.maxYaw;
  73696. }
  73697. else {
  73698. this.maxYaw = Math.PI;
  73699. }
  73700. if (options.minYaw != null) {
  73701. this.minYaw = options.minYaw;
  73702. }
  73703. else {
  73704. this.minYaw = -Math.PI;
  73705. }
  73706. if (options.maxPitch != null) {
  73707. this.maxPitch = options.maxPitch;
  73708. }
  73709. else {
  73710. this.maxPitch = Math.PI;
  73711. }
  73712. if (options.minPitch != null) {
  73713. this.minPitch = options.minPitch;
  73714. }
  73715. else {
  73716. this.minPitch = -Math.PI;
  73717. }
  73718. if (options.slerpAmount != null) {
  73719. this.slerpAmount = options.slerpAmount;
  73720. }
  73721. if (options.upAxis != null) {
  73722. this.upAxis = options.upAxis;
  73723. }
  73724. if (options.upAxisSpace != null) {
  73725. this.upAxisSpace = options.upAxisSpace;
  73726. }
  73727. if (options.yawAxis != null || options.pitchAxis != null) {
  73728. var newYawAxis = BABYLON.Axis.Y;
  73729. var newPitchAxis = BABYLON.Axis.X;
  73730. if (options.yawAxis != null) {
  73731. newYawAxis = options.yawAxis.clone();
  73732. newYawAxis.normalize();
  73733. }
  73734. if (options.pitchAxis != null) {
  73735. newPitchAxis = options.pitchAxis.clone();
  73736. newPitchAxis.normalize();
  73737. }
  73738. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73739. this._transformYawPitch = BABYLON.Matrix.Identity();
  73740. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73741. this._transformYawPitchInv = this._transformYawPitch.clone();
  73742. this._transformYawPitch.invert();
  73743. }
  73744. }
  73745. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73746. this.upAxisSpace = BABYLON.Space.LOCAL;
  73747. }
  73748. }
  73749. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73750. /**
  73751. * Get/set the minimum yaw angle that the bone can look to.
  73752. */
  73753. get: function () {
  73754. return this._minYaw;
  73755. },
  73756. set: function (value) {
  73757. this._minYaw = value;
  73758. this._minYawSin = Math.sin(value);
  73759. this._minYawCos = Math.cos(value);
  73760. if (this._maxYaw != null) {
  73761. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73762. this._yawRange = this._maxYaw - this._minYaw;
  73763. }
  73764. },
  73765. enumerable: true,
  73766. configurable: true
  73767. });
  73768. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73769. /**
  73770. * Get/set the maximum yaw angle that the bone can look to.
  73771. */
  73772. get: function () {
  73773. return this._maxYaw;
  73774. },
  73775. set: function (value) {
  73776. this._maxYaw = value;
  73777. this._maxYawSin = Math.sin(value);
  73778. this._maxYawCos = Math.cos(value);
  73779. if (this._minYaw != null) {
  73780. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73781. this._yawRange = this._maxYaw - this._minYaw;
  73782. }
  73783. },
  73784. enumerable: true,
  73785. configurable: true
  73786. });
  73787. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73788. /**
  73789. * Get/set the minimum pitch angle that the bone can look to.
  73790. */
  73791. get: function () {
  73792. return this._minPitch;
  73793. },
  73794. set: function (value) {
  73795. this._minPitch = value;
  73796. this._minPitchTan = Math.tan(value);
  73797. },
  73798. enumerable: true,
  73799. configurable: true
  73800. });
  73801. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73802. /**
  73803. * Get/set the maximum pitch angle that the bone can look to.
  73804. */
  73805. get: function () {
  73806. return this._maxPitch;
  73807. },
  73808. set: function (value) {
  73809. this._maxPitch = value;
  73810. this._maxPitchTan = Math.tan(value);
  73811. },
  73812. enumerable: true,
  73813. configurable: true
  73814. });
  73815. /**
  73816. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73817. */
  73818. BoneLookController.prototype.update = function () {
  73819. //skip the first frame when slerping so that the mesh rotation is correct
  73820. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73821. this._firstFrameSkipped = true;
  73822. return;
  73823. }
  73824. var bone = this.bone;
  73825. var bonePos = BoneLookController._tmpVecs[0];
  73826. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73827. var target = this.target;
  73828. var _tmpMat1 = BoneLookController._tmpMats[0];
  73829. var _tmpMat2 = BoneLookController._tmpMats[1];
  73830. var mesh = this.mesh;
  73831. var parentBone = bone.getParent();
  73832. var upAxis = BoneLookController._tmpVecs[1];
  73833. upAxis.copyFrom(this.upAxis);
  73834. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73835. if (this._transformYawPitch) {
  73836. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73837. }
  73838. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73839. }
  73840. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73841. mesh.getDirectionToRef(upAxis, upAxis);
  73842. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73843. upAxis.normalize();
  73844. }
  73845. }
  73846. var checkYaw = false;
  73847. var checkPitch = false;
  73848. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73849. checkYaw = true;
  73850. }
  73851. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73852. checkPitch = true;
  73853. }
  73854. if (checkYaw || checkPitch) {
  73855. var spaceMat = BoneLookController._tmpMats[2];
  73856. var spaceMatInv = BoneLookController._tmpMats[3];
  73857. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73858. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73859. }
  73860. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73861. spaceMat.copyFrom(mesh.getWorldMatrix());
  73862. }
  73863. else {
  73864. var forwardAxis = BoneLookController._tmpVecs[2];
  73865. forwardAxis.copyFrom(this._fowardAxis);
  73866. if (this._transformYawPitch) {
  73867. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73868. }
  73869. if (parentBone) {
  73870. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73871. }
  73872. else {
  73873. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73874. }
  73875. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73876. rightAxis.normalize();
  73877. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73878. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73879. }
  73880. spaceMat.invertToRef(spaceMatInv);
  73881. var xzlen = null;
  73882. if (checkPitch) {
  73883. var localTarget = BoneLookController._tmpVecs[3];
  73884. target.subtractToRef(bonePos, localTarget);
  73885. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73886. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73887. var pitch = Math.atan2(localTarget.y, xzlen);
  73888. var newPitch = pitch;
  73889. if (pitch > this._maxPitch) {
  73890. localTarget.y = this._maxPitchTan * xzlen;
  73891. newPitch = this._maxPitch;
  73892. }
  73893. else if (pitch < this._minPitch) {
  73894. localTarget.y = this._minPitchTan * xzlen;
  73895. newPitch = this._minPitch;
  73896. }
  73897. if (pitch != newPitch) {
  73898. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73899. localTarget.addInPlace(bonePos);
  73900. target = localTarget;
  73901. }
  73902. }
  73903. if (checkYaw) {
  73904. var localTarget = BoneLookController._tmpVecs[4];
  73905. target.subtractToRef(bonePos, localTarget);
  73906. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73907. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73908. var newYaw = yaw;
  73909. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73910. if (xzlen == null) {
  73911. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73912. }
  73913. if (this._yawRange > Math.PI) {
  73914. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73915. localTarget.z = this._maxYawCos * xzlen;
  73916. localTarget.x = this._maxYawSin * xzlen;
  73917. newYaw = this._maxYaw;
  73918. }
  73919. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73920. localTarget.z = this._minYawCos * xzlen;
  73921. localTarget.x = this._minYawSin * xzlen;
  73922. newYaw = this._minYaw;
  73923. }
  73924. }
  73925. else {
  73926. if (yaw > this._maxYaw) {
  73927. localTarget.z = this._maxYawCos * xzlen;
  73928. localTarget.x = this._maxYawSin * xzlen;
  73929. newYaw = this._maxYaw;
  73930. }
  73931. else if (yaw < this._minYaw) {
  73932. localTarget.z = this._minYawCos * xzlen;
  73933. localTarget.x = this._minYawSin * xzlen;
  73934. newYaw = this._minYaw;
  73935. }
  73936. }
  73937. }
  73938. if (this._slerping && this._yawRange > Math.PI) {
  73939. //are we going to be crossing into the min/max region?
  73940. var boneFwd = BoneLookController._tmpVecs[8];
  73941. boneFwd.copyFrom(BABYLON.Axis.Z);
  73942. if (this._transformYawPitch) {
  73943. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73944. }
  73945. var boneRotMat = BoneLookController._tmpMats[4];
  73946. this._boneQuat.toRotationMatrix(boneRotMat);
  73947. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73948. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73949. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73950. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73951. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73952. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73953. if (angBtwTar > angBtwMidYaw) {
  73954. if (xzlen == null) {
  73955. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73956. }
  73957. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73958. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73959. if (angBtwMin < angBtwMax) {
  73960. newYaw = boneYaw + Math.PI * .75;
  73961. localTarget.z = Math.cos(newYaw) * xzlen;
  73962. localTarget.x = Math.sin(newYaw) * xzlen;
  73963. }
  73964. else {
  73965. newYaw = boneYaw - Math.PI * .75;
  73966. localTarget.z = Math.cos(newYaw) * xzlen;
  73967. localTarget.x = Math.sin(newYaw) * xzlen;
  73968. }
  73969. }
  73970. }
  73971. if (yaw != newYaw) {
  73972. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73973. localTarget.addInPlace(bonePos);
  73974. target = localTarget;
  73975. }
  73976. }
  73977. }
  73978. var zaxis = BoneLookController._tmpVecs[5];
  73979. var xaxis = BoneLookController._tmpVecs[6];
  73980. var yaxis = BoneLookController._tmpVecs[7];
  73981. var _tmpQuat = BoneLookController._tmpQuat;
  73982. target.subtractToRef(bonePos, zaxis);
  73983. zaxis.normalize();
  73984. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73985. xaxis.normalize();
  73986. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73987. yaxis.normalize();
  73988. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73989. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73990. return;
  73991. }
  73992. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73993. return;
  73994. }
  73995. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73996. return;
  73997. }
  73998. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73999. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  74000. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  74001. }
  74002. if (this.slerpAmount < 1) {
  74003. if (!this._slerping) {
  74004. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  74005. }
  74006. if (this._transformYawPitch) {
  74007. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74008. }
  74009. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  74010. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  74011. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  74012. this._slerping = true;
  74013. }
  74014. else {
  74015. if (this._transformYawPitch) {
  74016. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74017. }
  74018. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  74019. this._slerping = false;
  74020. }
  74021. };
  74022. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  74023. var angDiff = ang2 - ang1;
  74024. angDiff %= Math.PI * 2;
  74025. if (angDiff > Math.PI) {
  74026. angDiff -= Math.PI * 2;
  74027. }
  74028. else if (angDiff < -Math.PI) {
  74029. angDiff += Math.PI * 2;
  74030. }
  74031. return angDiff;
  74032. };
  74033. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  74034. ang1 %= (2 * Math.PI);
  74035. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74036. ang2 %= (2 * Math.PI);
  74037. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74038. var ab = 0;
  74039. if (ang1 < ang2) {
  74040. ab = ang2 - ang1;
  74041. }
  74042. else {
  74043. ab = ang1 - ang2;
  74044. }
  74045. if (ab > Math.PI) {
  74046. ab = Math.PI * 2 - ab;
  74047. }
  74048. return ab;
  74049. };
  74050. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  74051. ang %= (2 * Math.PI);
  74052. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  74053. ang1 %= (2 * Math.PI);
  74054. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74055. ang2 %= (2 * Math.PI);
  74056. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74057. if (ang1 < ang2) {
  74058. if (ang > ang1 && ang < ang2) {
  74059. return true;
  74060. }
  74061. }
  74062. else {
  74063. if (ang > ang2 && ang < ang1) {
  74064. return true;
  74065. }
  74066. }
  74067. return false;
  74068. };
  74069. 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()];
  74070. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  74071. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74072. return BoneLookController;
  74073. }());
  74074. BABYLON.BoneLookController = BoneLookController;
  74075. })(BABYLON || (BABYLON = {}));
  74076. //# sourceMappingURL=babylon.boneLookController.js.map
  74077. "use strict";
  74078. var BABYLON;
  74079. (function (BABYLON) {
  74080. var Skeleton = /** @class */ (function () {
  74081. function Skeleton(name, id, scene) {
  74082. this.name = name;
  74083. this.id = id;
  74084. this.bones = new Array();
  74085. this.needInitialSkinMatrix = false;
  74086. this._isDirty = true;
  74087. this._meshesWithPoseMatrix = new Array();
  74088. this._identity = BABYLON.Matrix.Identity();
  74089. this._ranges = {};
  74090. this._lastAbsoluteTransformsUpdateId = -1;
  74091. /**
  74092. * Specifies if the skeleton should be serialized.
  74093. */
  74094. this.doNotSerialize = false;
  74095. // Events
  74096. /**
  74097. * An event triggered before computing the skeleton's matrices
  74098. * @type {BABYLON.Observable}
  74099. */
  74100. this.onBeforeComputeObservable = new BABYLON.Observable();
  74101. this.bones = [];
  74102. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74103. scene.skeletons.push(this);
  74104. //make sure it will recalculate the matrix next time prepare is called.
  74105. this._isDirty = true;
  74106. }
  74107. // Members
  74108. Skeleton.prototype.getTransformMatrices = function (mesh) {
  74109. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  74110. return mesh._bonesTransformMatrices;
  74111. }
  74112. if (!this._transformMatrices) {
  74113. this.prepare();
  74114. }
  74115. return this._transformMatrices;
  74116. };
  74117. Skeleton.prototype.getScene = function () {
  74118. return this._scene;
  74119. };
  74120. // Methods
  74121. /**
  74122. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  74123. */
  74124. Skeleton.prototype.toString = function (fullDetails) {
  74125. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  74126. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  74127. if (fullDetails) {
  74128. ret += ", Ranges: {";
  74129. var first = true;
  74130. for (var name_1 in this._ranges) {
  74131. if (first) {
  74132. ret += ", ";
  74133. first = false;
  74134. }
  74135. ret += name_1;
  74136. }
  74137. ret += "}";
  74138. }
  74139. return ret;
  74140. };
  74141. /**
  74142. * Get bone's index searching by name
  74143. * @param {string} name is bone's name to search for
  74144. * @return {number} Indice of the bone. Returns -1 if not found
  74145. */
  74146. Skeleton.prototype.getBoneIndexByName = function (name) {
  74147. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  74148. if (this.bones[boneIndex].name === name) {
  74149. return boneIndex;
  74150. }
  74151. }
  74152. return -1;
  74153. };
  74154. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  74155. // check name not already in use
  74156. if (!this._ranges[name]) {
  74157. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  74158. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74159. if (this.bones[i].animations[0]) {
  74160. this.bones[i].animations[0].createRange(name, from, to);
  74161. }
  74162. }
  74163. }
  74164. };
  74165. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  74166. if (deleteFrames === void 0) { deleteFrames = true; }
  74167. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74168. if (this.bones[i].animations[0]) {
  74169. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  74170. }
  74171. }
  74172. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  74173. };
  74174. Skeleton.prototype.getAnimationRange = function (name) {
  74175. return this._ranges[name];
  74176. };
  74177. /**
  74178. * Returns as an Array, all AnimationRanges defined on this skeleton
  74179. */
  74180. Skeleton.prototype.getAnimationRanges = function () {
  74181. var animationRanges = [];
  74182. var name;
  74183. var i = 0;
  74184. for (name in this._ranges) {
  74185. animationRanges[i] = this._ranges[name];
  74186. i++;
  74187. }
  74188. return animationRanges;
  74189. };
  74190. /**
  74191. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  74192. */
  74193. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  74194. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  74195. if (this._ranges[name] || !source.getAnimationRange(name)) {
  74196. return false;
  74197. }
  74198. var ret = true;
  74199. var frameOffset = this._getHighestAnimationFrame() + 1;
  74200. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  74201. var boneDict = {};
  74202. var sourceBones = source.bones;
  74203. var nBones;
  74204. var i;
  74205. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  74206. boneDict[sourceBones[i].name] = sourceBones[i];
  74207. }
  74208. if (this.bones.length !== sourceBones.length) {
  74209. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  74210. ret = false;
  74211. }
  74212. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  74213. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  74214. var boneName = this.bones[i].name;
  74215. var sourceBone = boneDict[boneName];
  74216. if (sourceBone) {
  74217. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  74218. }
  74219. else {
  74220. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  74221. ret = false;
  74222. }
  74223. }
  74224. // do not call createAnimationRange(), since it also is done to bones, which was already done
  74225. var range = source.getAnimationRange(name);
  74226. if (range) {
  74227. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  74228. }
  74229. return ret;
  74230. };
  74231. Skeleton.prototype.returnToRest = function () {
  74232. for (var index = 0; index < this.bones.length; index++) {
  74233. this.bones[index].returnToRest();
  74234. }
  74235. };
  74236. Skeleton.prototype._getHighestAnimationFrame = function () {
  74237. var ret = 0;
  74238. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74239. if (this.bones[i].animations[0]) {
  74240. var highest = this.bones[i].animations[0].getHighestFrame();
  74241. if (ret < highest) {
  74242. ret = highest;
  74243. }
  74244. }
  74245. }
  74246. return ret;
  74247. };
  74248. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  74249. var range = this.getAnimationRange(name);
  74250. if (!range) {
  74251. return null;
  74252. }
  74253. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  74254. };
  74255. Skeleton.prototype._markAsDirty = function () {
  74256. this._isDirty = true;
  74257. };
  74258. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  74259. this._meshesWithPoseMatrix.push(mesh);
  74260. };
  74261. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  74262. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  74263. if (index > -1) {
  74264. this._meshesWithPoseMatrix.splice(index, 1);
  74265. }
  74266. };
  74267. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  74268. this.onBeforeComputeObservable.notifyObservers(this);
  74269. for (var index = 0; index < this.bones.length; index++) {
  74270. var bone = this.bones[index];
  74271. var parentBone = bone.getParent();
  74272. if (parentBone) {
  74273. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  74274. }
  74275. else {
  74276. if (initialSkinMatrix) {
  74277. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  74278. }
  74279. else {
  74280. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  74281. }
  74282. }
  74283. if (bone._index !== -1) {
  74284. var mappedIndex = bone._index === null ? index : bone._index;
  74285. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  74286. }
  74287. }
  74288. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  74289. };
  74290. Skeleton.prototype.prepare = function () {
  74291. if (!this._isDirty) {
  74292. return;
  74293. }
  74294. if (this.needInitialSkinMatrix) {
  74295. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  74296. var mesh = this._meshesWithPoseMatrix[index];
  74297. var poseMatrix = mesh.getPoseMatrix();
  74298. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  74299. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74300. }
  74301. if (this._synchronizedWithMesh !== mesh) {
  74302. this._synchronizedWithMesh = mesh;
  74303. // Prepare bones
  74304. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  74305. var bone = this.bones[boneIndex];
  74306. if (!bone.getParent()) {
  74307. var matrix = bone.getBaseMatrix();
  74308. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74309. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74310. }
  74311. }
  74312. }
  74313. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74314. }
  74315. }
  74316. else {
  74317. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74318. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74319. }
  74320. this._computeTransformMatrices(this._transformMatrices, null);
  74321. }
  74322. this._isDirty = false;
  74323. this._scene._activeBones.addCount(this.bones.length, false);
  74324. };
  74325. Skeleton.prototype.getAnimatables = function () {
  74326. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74327. this._animatables = [];
  74328. for (var index = 0; index < this.bones.length; index++) {
  74329. this._animatables.push(this.bones[index]);
  74330. }
  74331. }
  74332. return this._animatables;
  74333. };
  74334. Skeleton.prototype.clone = function (name, id) {
  74335. var result = new Skeleton(name, id || name, this._scene);
  74336. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74337. for (var index = 0; index < this.bones.length; index++) {
  74338. var source = this.bones[index];
  74339. var parentBone = null;
  74340. var parent_1 = source.getParent();
  74341. if (parent_1) {
  74342. var parentIndex = this.bones.indexOf(parent_1);
  74343. parentBone = result.bones[parentIndex];
  74344. }
  74345. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74346. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74347. }
  74348. if (this._ranges) {
  74349. result._ranges = {};
  74350. for (var rangeName in this._ranges) {
  74351. var range = this._ranges[rangeName];
  74352. if (range) {
  74353. result._ranges[rangeName] = range.clone();
  74354. }
  74355. }
  74356. }
  74357. this._isDirty = true;
  74358. return result;
  74359. };
  74360. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74361. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74362. this.bones.forEach(function (bone) {
  74363. bone.animations.forEach(function (animation) {
  74364. animation.enableBlending = true;
  74365. animation.blendingSpeed = blendingSpeed;
  74366. });
  74367. });
  74368. };
  74369. Skeleton.prototype.dispose = function () {
  74370. this._meshesWithPoseMatrix = [];
  74371. // Animations
  74372. this.getScene().stopAnimation(this);
  74373. // Remove from scene
  74374. this.getScene().removeSkeleton(this);
  74375. };
  74376. Skeleton.prototype.serialize = function () {
  74377. var serializationObject = {};
  74378. serializationObject.name = this.name;
  74379. serializationObject.id = this.id;
  74380. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  74381. serializationObject.bones = [];
  74382. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74383. for (var index = 0; index < this.bones.length; index++) {
  74384. var bone = this.bones[index];
  74385. var parent_2 = bone.getParent();
  74386. var serializedBone = {
  74387. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74388. name: bone.name,
  74389. matrix: bone.getBaseMatrix().toArray(),
  74390. rest: bone.getRestPose().toArray()
  74391. };
  74392. serializationObject.bones.push(serializedBone);
  74393. if (bone.length) {
  74394. serializedBone.length = bone.length;
  74395. }
  74396. if (bone.animations && bone.animations.length > 0) {
  74397. serializedBone.animation = bone.animations[0].serialize();
  74398. }
  74399. serializationObject.ranges = [];
  74400. for (var name in this._ranges) {
  74401. var source = this._ranges[name];
  74402. if (!source) {
  74403. continue;
  74404. }
  74405. var range = {};
  74406. range.name = name;
  74407. range.from = source.from;
  74408. range.to = source.to;
  74409. serializationObject.ranges.push(range);
  74410. }
  74411. }
  74412. return serializationObject;
  74413. };
  74414. Skeleton.Parse = function (parsedSkeleton, scene) {
  74415. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74416. if (parsedSkeleton.dimensionsAtRest) {
  74417. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74418. }
  74419. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74420. var index;
  74421. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74422. var parsedBone = parsedSkeleton.bones[index];
  74423. var parentBone = null;
  74424. if (parsedBone.parentBoneIndex > -1) {
  74425. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74426. }
  74427. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74428. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74429. if (parsedBone.length) {
  74430. bone.length = parsedBone.length;
  74431. }
  74432. if (parsedBone.animation) {
  74433. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74434. }
  74435. }
  74436. // placed after bones, so createAnimationRange can cascade down
  74437. if (parsedSkeleton.ranges) {
  74438. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74439. var data = parsedSkeleton.ranges[index];
  74440. skeleton.createAnimationRange(data.name, data.from, data.to);
  74441. }
  74442. }
  74443. return skeleton;
  74444. };
  74445. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74446. if (forceUpdate === void 0) { forceUpdate = false; }
  74447. var renderId = this._scene.getRenderId();
  74448. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74449. this.bones[0].computeAbsoluteTransforms();
  74450. this._lastAbsoluteTransformsUpdateId = renderId;
  74451. }
  74452. };
  74453. Skeleton.prototype.getPoseMatrix = function () {
  74454. var poseMatrix = null;
  74455. if (this._meshesWithPoseMatrix.length > 0) {
  74456. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74457. }
  74458. return poseMatrix;
  74459. };
  74460. Skeleton.prototype.sortBones = function () {
  74461. var bones = new Array();
  74462. var visited = new Array(this.bones.length);
  74463. for (var index = 0; index < this.bones.length; index++) {
  74464. this._sortBones(index, bones, visited);
  74465. }
  74466. this.bones = bones;
  74467. };
  74468. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74469. if (visited[index]) {
  74470. return;
  74471. }
  74472. visited[index] = true;
  74473. var bone = this.bones[index];
  74474. if (bone._index === undefined) {
  74475. bone._index = index;
  74476. }
  74477. var parentBone = bone.getParent();
  74478. if (parentBone) {
  74479. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74480. }
  74481. bones.push(bone);
  74482. };
  74483. return Skeleton;
  74484. }());
  74485. BABYLON.Skeleton = Skeleton;
  74486. })(BABYLON || (BABYLON = {}));
  74487. //# sourceMappingURL=babylon.skeleton.js.map
  74488. "use strict";
  74489. var BABYLON;
  74490. (function (BABYLON) {
  74491. var SphericalPolynomial = /** @class */ (function () {
  74492. function SphericalPolynomial() {
  74493. this.x = BABYLON.Vector3.Zero();
  74494. this.y = BABYLON.Vector3.Zero();
  74495. this.z = BABYLON.Vector3.Zero();
  74496. this.xx = BABYLON.Vector3.Zero();
  74497. this.yy = BABYLON.Vector3.Zero();
  74498. this.zz = BABYLON.Vector3.Zero();
  74499. this.xy = BABYLON.Vector3.Zero();
  74500. this.yz = BABYLON.Vector3.Zero();
  74501. this.zx = BABYLON.Vector3.Zero();
  74502. }
  74503. SphericalPolynomial.prototype.addAmbient = function (color) {
  74504. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74505. this.xx = this.xx.add(colorVector);
  74506. this.yy = this.yy.add(colorVector);
  74507. this.zz = this.zz.add(colorVector);
  74508. };
  74509. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74510. var result = new SphericalPolynomial();
  74511. result.x = harmonics.L11.scale(1.02333);
  74512. result.y = harmonics.L1_1.scale(1.02333);
  74513. result.z = harmonics.L10.scale(1.02333);
  74514. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74515. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74516. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74517. result.yz = harmonics.L2_1.scale(0.858086);
  74518. result.zx = harmonics.L21.scale(0.858086);
  74519. result.xy = harmonics.L2_2.scale(0.858086);
  74520. result.scale(1.0 / Math.PI);
  74521. return result;
  74522. };
  74523. SphericalPolynomial.prototype.scale = function (scale) {
  74524. this.x = this.x.scale(scale);
  74525. this.y = this.y.scale(scale);
  74526. this.z = this.z.scale(scale);
  74527. this.xx = this.xx.scale(scale);
  74528. this.yy = this.yy.scale(scale);
  74529. this.zz = this.zz.scale(scale);
  74530. this.yz = this.yz.scale(scale);
  74531. this.zx = this.zx.scale(scale);
  74532. this.xy = this.xy.scale(scale);
  74533. };
  74534. return SphericalPolynomial;
  74535. }());
  74536. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74537. var SphericalHarmonics = /** @class */ (function () {
  74538. function SphericalHarmonics() {
  74539. this.L00 = BABYLON.Vector3.Zero();
  74540. this.L1_1 = BABYLON.Vector3.Zero();
  74541. this.L10 = BABYLON.Vector3.Zero();
  74542. this.L11 = BABYLON.Vector3.Zero();
  74543. this.L2_2 = BABYLON.Vector3.Zero();
  74544. this.L2_1 = BABYLON.Vector3.Zero();
  74545. this.L20 = BABYLON.Vector3.Zero();
  74546. this.L21 = BABYLON.Vector3.Zero();
  74547. this.L22 = BABYLON.Vector3.Zero();
  74548. }
  74549. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74550. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74551. var c = colorVector.scale(deltaSolidAngle);
  74552. this.L00 = this.L00.add(c.scale(0.282095));
  74553. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74554. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74555. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74556. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74557. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74558. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74559. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74560. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74561. };
  74562. SphericalHarmonics.prototype.scale = function (scale) {
  74563. this.L00 = this.L00.scale(scale);
  74564. this.L1_1 = this.L1_1.scale(scale);
  74565. this.L10 = this.L10.scale(scale);
  74566. this.L11 = this.L11.scale(scale);
  74567. this.L2_2 = this.L2_2.scale(scale);
  74568. this.L2_1 = this.L2_1.scale(scale);
  74569. this.L20 = this.L20.scale(scale);
  74570. this.L21 = this.L21.scale(scale);
  74571. this.L22 = this.L22.scale(scale);
  74572. };
  74573. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74574. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74575. //
  74576. // E_lm = A_l * L_lm
  74577. //
  74578. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74579. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74580. // the scaling factors are given in equation 9.
  74581. // Constant (Band 0)
  74582. this.L00 = this.L00.scale(3.141593);
  74583. // Linear (Band 1)
  74584. this.L1_1 = this.L1_1.scale(2.094395);
  74585. this.L10 = this.L10.scale(2.094395);
  74586. this.L11 = this.L11.scale(2.094395);
  74587. // Quadratic (Band 2)
  74588. this.L2_2 = this.L2_2.scale(0.785398);
  74589. this.L2_1 = this.L2_1.scale(0.785398);
  74590. this.L20 = this.L20.scale(0.785398);
  74591. this.L21 = this.L21.scale(0.785398);
  74592. this.L22 = this.L22.scale(0.785398);
  74593. };
  74594. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74595. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74596. // L = (1/pi) * E * rho
  74597. //
  74598. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74599. this.scale(1.0 / Math.PI);
  74600. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74601. // (The pixel shader must apply albedo after texture fetches, etc).
  74602. };
  74603. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74604. var result = new SphericalHarmonics();
  74605. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74606. result.L1_1 = polynomial.y.scale(0.977204);
  74607. result.L10 = polynomial.z.scale(0.977204);
  74608. result.L11 = polynomial.x.scale(0.977204);
  74609. result.L2_2 = polynomial.xy.scale(1.16538);
  74610. result.L2_1 = polynomial.yz.scale(1.16538);
  74611. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74612. result.L21 = polynomial.zx.scale(1.16538);
  74613. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74614. result.scale(Math.PI);
  74615. return result;
  74616. };
  74617. return SphericalHarmonics;
  74618. }());
  74619. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74620. })(BABYLON || (BABYLON = {}));
  74621. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74622. "use strict";
  74623. var BABYLON;
  74624. (function (BABYLON) {
  74625. var FileFaceOrientation = /** @class */ (function () {
  74626. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74627. this.name = name;
  74628. this.worldAxisForNormal = worldAxisForNormal;
  74629. this.worldAxisForFileX = worldAxisForFileX;
  74630. this.worldAxisForFileY = worldAxisForFileY;
  74631. }
  74632. return FileFaceOrientation;
  74633. }());
  74634. ;
  74635. /**
  74636. * Helper class dealing with the extraction of spherical polynomial dataArray
  74637. * from a cube map.
  74638. */
  74639. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74640. function CubeMapToSphericalPolynomialTools() {
  74641. }
  74642. /**
  74643. * Converts a texture to the according Spherical Polynomial data.
  74644. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74645. *
  74646. * @param texture The texture to extract the information from.
  74647. * @return The Spherical Polynomial data.
  74648. */
  74649. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74650. if (!texture.isCube) {
  74651. // Only supports cube Textures currently.
  74652. return null;
  74653. }
  74654. var size = texture.getSize().width;
  74655. var right = texture.readPixels(0);
  74656. var left = texture.readPixels(1);
  74657. var up;
  74658. var down;
  74659. if (texture.isRenderTarget) {
  74660. up = texture.readPixels(3);
  74661. down = texture.readPixels(2);
  74662. }
  74663. else {
  74664. up = texture.readPixels(2);
  74665. down = texture.readPixels(3);
  74666. }
  74667. var front = texture.readPixels(4);
  74668. var back = texture.readPixels(5);
  74669. var gammaSpace = texture.gammaSpace;
  74670. // Always read as RGBA.
  74671. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74672. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74673. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74674. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74675. }
  74676. var cubeInfo = {
  74677. size: size,
  74678. right: right,
  74679. left: left,
  74680. up: up,
  74681. down: down,
  74682. front: front,
  74683. back: back,
  74684. format: format,
  74685. type: type,
  74686. gammaSpace: gammaSpace,
  74687. };
  74688. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74689. };
  74690. /**
  74691. * Converts a cubemap to the according Spherical Polynomial data.
  74692. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74693. *
  74694. * @param cubeInfo The Cube map to extract the information from.
  74695. * @return The Spherical Polynomial data.
  74696. */
  74697. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74698. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74699. var totalSolidAngle = 0.0;
  74700. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74701. var du = 2.0 / cubeInfo.size;
  74702. var dv = du;
  74703. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74704. var minUV = du * 0.5 - 1.0;
  74705. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74706. var fileFace = this.FileFaces[faceIndex];
  74707. var dataArray = cubeInfo[fileFace.name];
  74708. var v = minUV;
  74709. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74710. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74711. // Because SP is still linear, so summation is fine in that basis.
  74712. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74713. for (var y = 0; y < cubeInfo.size; y++) {
  74714. var u = minUV;
  74715. for (var x = 0; x < cubeInfo.size; x++) {
  74716. // World direction (not normalised)
  74717. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74718. worldDirection.normalize();
  74719. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74720. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74721. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74722. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74723. // Handle Integer types.
  74724. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74725. r /= 255;
  74726. g /= 255;
  74727. b /= 255;
  74728. }
  74729. // Handle Gamma space textures.
  74730. if (cubeInfo.gammaSpace) {
  74731. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74732. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74733. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74734. }
  74735. var color = new BABYLON.Color3(r, g, b);
  74736. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74737. totalSolidAngle += deltaSolidAngle;
  74738. u += du;
  74739. }
  74740. v += dv;
  74741. }
  74742. }
  74743. // Solid angle for entire sphere is 4*pi
  74744. var sphereSolidAngle = 4.0 * Math.PI;
  74745. // Adjust the solid angle to allow for how many faces we processed.
  74746. var facesProcessed = 6.0;
  74747. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74748. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74749. // This is needed because the numerical integration over the cube uses a
  74750. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74751. // and also to compensate for accumulative error due to float precision in the summation.
  74752. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74753. sphericalHarmonics.scale(correctionFactor);
  74754. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74755. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74756. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74757. };
  74758. CubeMapToSphericalPolynomialTools.FileFaces = [
  74759. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74760. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74761. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74762. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74763. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74764. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74765. ];
  74766. return CubeMapToSphericalPolynomialTools;
  74767. }());
  74768. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74769. })(BABYLON || (BABYLON = {}));
  74770. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74771. "use strict";
  74772. var BABYLON;
  74773. (function (BABYLON) {
  74774. /**
  74775. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74776. */
  74777. var PanoramaToCubeMapTools = /** @class */ (function () {
  74778. function PanoramaToCubeMapTools() {
  74779. }
  74780. /**
  74781. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74782. *
  74783. * @param float32Array The source data.
  74784. * @param inputWidth The width of the input panorama.
  74785. * @param inputhHeight The height of the input panorama.
  74786. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74787. * @return The cubemap data
  74788. */
  74789. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74790. if (!float32Array) {
  74791. throw "ConvertPanoramaToCubemap: input cannot be null";
  74792. }
  74793. if (float32Array.length != inputWidth * inputHeight * 3) {
  74794. throw "ConvertPanoramaToCubemap: input size is wrong";
  74795. }
  74796. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74797. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74798. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74799. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74800. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74801. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74802. return {
  74803. front: textureFront,
  74804. back: textureBack,
  74805. left: textureLeft,
  74806. right: textureRight,
  74807. up: textureUp,
  74808. down: textureDown,
  74809. size: size,
  74810. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74811. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74812. gammaSpace: false,
  74813. };
  74814. };
  74815. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74816. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74817. var textureArray = new Float32Array(buffer);
  74818. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74819. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74820. var dy = 1 / texSize;
  74821. var fy = 0;
  74822. for (var y = 0; y < texSize; y++) {
  74823. var xv1 = faceData[0];
  74824. var xv2 = faceData[2];
  74825. for (var x = 0; x < texSize; x++) {
  74826. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74827. v.normalize();
  74828. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74829. // 3 channels per pixels
  74830. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74831. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74832. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74833. xv1 = xv1.add(rotDX1);
  74834. xv2 = xv2.add(rotDX2);
  74835. }
  74836. fy += dy;
  74837. }
  74838. return textureArray;
  74839. };
  74840. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74841. var theta = Math.atan2(vDir.z, vDir.x);
  74842. var phi = Math.acos(vDir.y);
  74843. while (theta < -Math.PI)
  74844. theta += 2 * Math.PI;
  74845. while (theta > Math.PI)
  74846. theta -= 2 * Math.PI;
  74847. var dx = theta / Math.PI;
  74848. var dy = phi / Math.PI;
  74849. // recenter.
  74850. dx = dx * 0.5 + 0.5;
  74851. var px = Math.round(dx * inputWidth);
  74852. if (px < 0)
  74853. px = 0;
  74854. else if (px >= inputWidth)
  74855. px = inputWidth - 1;
  74856. var py = Math.round(dy * inputHeight);
  74857. if (py < 0)
  74858. py = 0;
  74859. else if (py >= inputHeight)
  74860. py = inputHeight - 1;
  74861. var inputY = (inputHeight - py - 1);
  74862. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74863. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74864. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74865. return {
  74866. r: r,
  74867. g: g,
  74868. b: b
  74869. };
  74870. };
  74871. PanoramaToCubeMapTools.FACE_FRONT = [
  74872. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74873. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74874. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74875. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74876. ];
  74877. PanoramaToCubeMapTools.FACE_BACK = [
  74878. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74879. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74880. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74881. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74882. ];
  74883. PanoramaToCubeMapTools.FACE_RIGHT = [
  74884. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74885. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74886. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74887. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74888. ];
  74889. PanoramaToCubeMapTools.FACE_LEFT = [
  74890. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74891. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74892. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74893. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74894. ];
  74895. PanoramaToCubeMapTools.FACE_DOWN = [
  74896. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74897. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74898. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74899. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74900. ];
  74901. PanoramaToCubeMapTools.FACE_UP = [
  74902. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74903. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74904. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74905. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74906. ];
  74907. return PanoramaToCubeMapTools;
  74908. }());
  74909. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74910. })(BABYLON || (BABYLON = {}));
  74911. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74912. "use strict";
  74913. var BABYLON;
  74914. (function (BABYLON) {
  74915. ;
  74916. /**
  74917. * This groups tools to convert HDR texture to native colors array.
  74918. */
  74919. var HDRTools = /** @class */ (function () {
  74920. function HDRTools() {
  74921. }
  74922. HDRTools.Ldexp = function (mantissa, exponent) {
  74923. if (exponent > 1023) {
  74924. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74925. }
  74926. if (exponent < -1074) {
  74927. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74928. }
  74929. return mantissa * Math.pow(2, exponent);
  74930. };
  74931. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74932. if (exponent > 0) {
  74933. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74934. float32array[index + 0] = red * exponent;
  74935. float32array[index + 1] = green * exponent;
  74936. float32array[index + 2] = blue * exponent;
  74937. }
  74938. else {
  74939. float32array[index + 0] = 0;
  74940. float32array[index + 1] = 0;
  74941. float32array[index + 2] = 0;
  74942. }
  74943. };
  74944. HDRTools.readStringLine = function (uint8array, startIndex) {
  74945. var line = "";
  74946. var character = "";
  74947. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74948. character = String.fromCharCode(uint8array[i]);
  74949. if (character == "\n") {
  74950. break;
  74951. }
  74952. line += character;
  74953. }
  74954. return line;
  74955. };
  74956. /**
  74957. * Reads header information from an RGBE texture stored in a native array.
  74958. * More information on this format are available here:
  74959. * https://en.wikipedia.org/wiki/RGBE_image_format
  74960. *
  74961. * @param uint8array The binary file stored in native array.
  74962. * @return The header information.
  74963. */
  74964. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74965. var height = 0;
  74966. var width = 0;
  74967. var line = this.readStringLine(uint8array, 0);
  74968. if (line[0] != '#' || line[1] != '?') {
  74969. throw "Bad HDR Format.";
  74970. }
  74971. var endOfHeader = false;
  74972. var findFormat = false;
  74973. var lineIndex = 0;
  74974. do {
  74975. lineIndex += (line.length + 1);
  74976. line = this.readStringLine(uint8array, lineIndex);
  74977. if (line == "FORMAT=32-bit_rle_rgbe") {
  74978. findFormat = true;
  74979. }
  74980. else if (line.length == 0) {
  74981. endOfHeader = true;
  74982. }
  74983. } while (!endOfHeader);
  74984. if (!findFormat) {
  74985. throw "HDR Bad header format, unsupported FORMAT";
  74986. }
  74987. lineIndex += (line.length + 1);
  74988. line = this.readStringLine(uint8array, lineIndex);
  74989. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74990. var match = sizeRegexp.exec(line);
  74991. // TODO. Support +Y and -X if needed.
  74992. if (!match || match.length < 3) {
  74993. throw "HDR Bad header format, no size";
  74994. }
  74995. width = parseInt(match[2]);
  74996. height = parseInt(match[1]);
  74997. if (width < 8 || width > 0x7fff) {
  74998. throw "HDR Bad header format, unsupported size";
  74999. }
  75000. lineIndex += (line.length + 1);
  75001. return {
  75002. height: height,
  75003. width: width,
  75004. dataPosition: lineIndex
  75005. };
  75006. };
  75007. /**
  75008. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  75009. * This RGBE texture needs to store the information as a panorama.
  75010. *
  75011. * More information on this format are available here:
  75012. * https://en.wikipedia.org/wiki/RGBE_image_format
  75013. *
  75014. * @param buffer The binary file stored in an array buffer.
  75015. * @param size The expected size of the extracted cubemap.
  75016. * @return The Cube Map information.
  75017. */
  75018. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  75019. var uint8array = new Uint8Array(buffer);
  75020. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  75021. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75022. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  75023. return cubeMapData;
  75024. };
  75025. /**
  75026. * Returns the pixels data extracted from an RGBE texture.
  75027. * This pixels will be stored left to right up to down in the R G B order in one array.
  75028. *
  75029. * More information on this format are available here:
  75030. * https://en.wikipedia.org/wiki/RGBE_image_format
  75031. *
  75032. * @param uint8array The binary file stored in an array buffer.
  75033. * @param hdrInfo The header information of the file.
  75034. * @return The pixels data in RGB right to left up to down order.
  75035. */
  75036. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  75037. // Keep for multi format supports.
  75038. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75039. };
  75040. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  75041. var num_scanlines = hdrInfo.height;
  75042. var scanline_width = hdrInfo.width;
  75043. var a, b, c, d, count;
  75044. var dataIndex = hdrInfo.dataPosition;
  75045. var index = 0, endIndex = 0, i = 0;
  75046. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  75047. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  75048. // 3 channels of 4 bytes per pixel in float.
  75049. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  75050. var resultArray = new Float32Array(resultBuffer);
  75051. // read in each successive scanline
  75052. while (num_scanlines > 0) {
  75053. a = uint8array[dataIndex++];
  75054. b = uint8array[dataIndex++];
  75055. c = uint8array[dataIndex++];
  75056. d = uint8array[dataIndex++];
  75057. if (a != 2 || b != 2 || (c & 0x80)) {
  75058. // this file is not run length encoded
  75059. throw "HDR Bad header format, not RLE";
  75060. }
  75061. if (((c << 8) | d) != scanline_width) {
  75062. throw "HDR Bad header format, wrong scan line width";
  75063. }
  75064. index = 0;
  75065. // read each of the four channels for the scanline into the buffer
  75066. for (i = 0; i < 4; i++) {
  75067. endIndex = (i + 1) * scanline_width;
  75068. while (index < endIndex) {
  75069. a = uint8array[dataIndex++];
  75070. b = uint8array[dataIndex++];
  75071. if (a > 128) {
  75072. // a run of the same value
  75073. count = a - 128;
  75074. if ((count == 0) || (count > endIndex - index)) {
  75075. throw "HDR Bad Format, bad scanline data (run)";
  75076. }
  75077. while (count-- > 0) {
  75078. scanLineArray[index++] = b;
  75079. }
  75080. }
  75081. else {
  75082. // a non-run
  75083. count = a;
  75084. if ((count == 0) || (count > endIndex - index)) {
  75085. throw "HDR Bad Format, bad scanline data (non-run)";
  75086. }
  75087. scanLineArray[index++] = b;
  75088. if (--count > 0) {
  75089. for (var j = 0; j < count; j++) {
  75090. scanLineArray[index++] = uint8array[dataIndex++];
  75091. }
  75092. }
  75093. }
  75094. }
  75095. }
  75096. // now convert data from buffer into floats
  75097. for (i = 0; i < scanline_width; i++) {
  75098. a = scanLineArray[i];
  75099. b = scanLineArray[i + scanline_width];
  75100. c = scanLineArray[i + 2 * scanline_width];
  75101. d = scanLineArray[i + 3 * scanline_width];
  75102. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  75103. }
  75104. num_scanlines--;
  75105. }
  75106. return resultArray;
  75107. };
  75108. return HDRTools;
  75109. }());
  75110. BABYLON.HDRTools = HDRTools;
  75111. })(BABYLON || (BABYLON = {}));
  75112. //# sourceMappingURL=babylon.hdr.js.map
  75113. "use strict";
  75114. var BABYLON;
  75115. (function (BABYLON) {
  75116. /**
  75117. * This represents a texture coming from an HDR input.
  75118. *
  75119. * The only supported format is currently panorama picture stored in RGBE format.
  75120. * Example of such files can be found on HDRLib: http://hdrlib.com/
  75121. */
  75122. var HDRCubeTexture = /** @class */ (function (_super) {
  75123. __extends(HDRCubeTexture, _super);
  75124. /**
  75125. * Instantiates an HDRTexture from the following parameters.
  75126. *
  75127. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  75128. * @param scene The scene the texture will be used in
  75129. * @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.
  75130. * @param noMipmap Forces to not generate the mipmap if true
  75131. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  75132. * @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)
  75133. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  75134. */
  75135. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  75136. if (noMipmap === void 0) { noMipmap = false; }
  75137. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75138. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75139. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75140. if (onLoad === void 0) { onLoad = null; }
  75141. if (onError === void 0) { onError = null; }
  75142. var _this = _super.call(this, scene) || this;
  75143. _this._useInGammaSpace = false;
  75144. _this._generateHarmonics = true;
  75145. _this._isBABYLONPreprocessed = false;
  75146. _this._onLoad = null;
  75147. _this._onError = null;
  75148. /**
  75149. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  75150. */
  75151. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  75152. /**
  75153. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  75154. * This is usefull at run time to apply the good shader.
  75155. */
  75156. _this.isPMREM = false;
  75157. _this._isBlocking = true;
  75158. /**
  75159. * Gets or sets the center of the bounding box associated with the cube texture
  75160. * It must define where the camera used to render the texture was set
  75161. */
  75162. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  75163. if (!url) {
  75164. return _this;
  75165. }
  75166. _this.name = url;
  75167. _this.url = url;
  75168. _this.hasAlpha = false;
  75169. _this.isCube = true;
  75170. _this._textureMatrix = BABYLON.Matrix.Identity();
  75171. _this._onLoad = onLoad;
  75172. _this._onError = onError;
  75173. _this.gammaSpace = false;
  75174. var caps = scene.getEngine().getCaps();
  75175. if (size) {
  75176. _this._isBABYLONPreprocessed = false;
  75177. _this._noMipmap = noMipmap;
  75178. _this._size = size;
  75179. _this._useInGammaSpace = useInGammaSpace;
  75180. _this._usePMREMGenerator = usePMREMGenerator &&
  75181. caps.textureLOD &&
  75182. caps.textureFloat &&
  75183. !_this._useInGammaSpace;
  75184. }
  75185. else {
  75186. _this._isBABYLONPreprocessed = true;
  75187. _this._noMipmap = false;
  75188. _this._useInGammaSpace = false;
  75189. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  75190. !_this._useInGammaSpace;
  75191. }
  75192. _this.isPMREM = _this._usePMREMGenerator;
  75193. _this._texture = _this._getFromCache(url, _this._noMipmap);
  75194. if (!_this._texture) {
  75195. if (!scene.useDelayedTextureLoading) {
  75196. _this.loadTexture();
  75197. }
  75198. else {
  75199. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  75200. }
  75201. }
  75202. return _this;
  75203. }
  75204. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  75205. /**
  75206. * Gets wether or not the texture is blocking during loading.
  75207. */
  75208. get: function () {
  75209. return this._isBlocking;
  75210. },
  75211. /**
  75212. * Sets wether or not the texture is blocking during loading.
  75213. */
  75214. set: function (value) {
  75215. this._isBlocking = value;
  75216. },
  75217. enumerable: true,
  75218. configurable: true
  75219. });
  75220. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  75221. get: function () {
  75222. return this._boundingBoxSize;
  75223. },
  75224. /**
  75225. * Gets or sets the size of the bounding box associated with the cube texture
  75226. * When defined, the cubemap will switch to local mode
  75227. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  75228. * @example https://www.babylonjs-playground.com/#RNASML
  75229. */
  75230. set: function (value) {
  75231. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  75232. return;
  75233. }
  75234. this._boundingBoxSize = value;
  75235. var scene = this.getScene();
  75236. if (scene) {
  75237. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  75238. }
  75239. },
  75240. enumerable: true,
  75241. configurable: true
  75242. });
  75243. /**
  75244. * Occurs when the file is a preprocessed .babylon.hdr file.
  75245. */
  75246. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  75247. var _this = this;
  75248. var mipLevels = 0;
  75249. var floatArrayView = null;
  75250. var scene = this.getScene();
  75251. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  75252. var mips = new Array();
  75253. if (!floatArrayView) {
  75254. return mips;
  75255. }
  75256. var startIndex = 30;
  75257. for (var level = 0; level < mipLevels; level++) {
  75258. mips.push([]);
  75259. // Fill each pixel of the mip level.
  75260. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  75261. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75262. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  75263. mips[level].push(faceData);
  75264. startIndex += faceSize;
  75265. }
  75266. }
  75267. return mips;
  75268. } : null;
  75269. var callback = function (buffer) {
  75270. var scene = _this.getScene();
  75271. if (!scene) {
  75272. return null;
  75273. }
  75274. // Create Native Array Views
  75275. var intArrayView = new Int32Array(buffer);
  75276. floatArrayView = new Float32Array(buffer);
  75277. // Fill header.
  75278. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  75279. _this._size = intArrayView[1]; // CubeMap max mip face size.
  75280. // Update Texture Information.
  75281. if (!_this._texture) {
  75282. return null;
  75283. }
  75284. _this._texture.updateSize(_this._size, _this._size);
  75285. // Fill polynomial information.
  75286. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  75287. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  75288. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  75289. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  75290. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  75291. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  75292. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  75293. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  75294. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  75295. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  75296. _this.sphericalPolynomial = sphericalPolynomial;
  75297. // Fill pixel data.
  75298. mipLevels = intArrayView[29]; // Number of mip levels.
  75299. var startIndex = 30;
  75300. var data = [];
  75301. var faceSize = Math.pow(_this._size, 2) * 3;
  75302. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75303. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  75304. startIndex += faceSize;
  75305. }
  75306. var results = [];
  75307. var byteArray = null;
  75308. // Push each faces.
  75309. for (var k = 0; k < 6; k++) {
  75310. var dataFace = null;
  75311. // To be deprecated.
  75312. if (version === 1) {
  75313. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75314. dataFace = data[j];
  75315. }
  75316. // If special cases.
  75317. if (!mipmapGenerator && dataFace) {
  75318. if (!scene.getEngine().getCaps().textureFloat) {
  75319. // 3 channels of 1 bytes per pixel in bytes.
  75320. var byteBuffer = new ArrayBuffer(faceSize);
  75321. byteArray = new Uint8Array(byteBuffer);
  75322. }
  75323. for (var i = 0; i < _this._size * _this._size; i++) {
  75324. // Put in gamma space if requested.
  75325. if (_this._useInGammaSpace) {
  75326. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75327. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75328. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75329. }
  75330. // Convert to int texture for fallback.
  75331. if (byteArray) {
  75332. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75333. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75334. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75335. // May use luminance instead if the result is not accurate.
  75336. var max = Math.max(Math.max(r, g), b);
  75337. if (max > 255) {
  75338. var scale = 255 / max;
  75339. r *= scale;
  75340. g *= scale;
  75341. b *= scale;
  75342. }
  75343. byteArray[(i * 3) + 0] = r;
  75344. byteArray[(i * 3) + 1] = g;
  75345. byteArray[(i * 3) + 2] = b;
  75346. }
  75347. }
  75348. }
  75349. // Fill the array accordingly.
  75350. if (byteArray) {
  75351. results.push(byteArray);
  75352. }
  75353. else {
  75354. results.push(dataFace);
  75355. }
  75356. }
  75357. return results;
  75358. };
  75359. if (scene) {
  75360. 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);
  75361. }
  75362. };
  75363. /**
  75364. * Occurs when the file is raw .hdr file.
  75365. */
  75366. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75367. var _this = this;
  75368. var callback = function (buffer) {
  75369. var scene = _this.getScene();
  75370. if (!scene) {
  75371. return null;
  75372. }
  75373. // Extract the raw linear data.
  75374. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75375. // Generate harmonics if needed.
  75376. if (_this._generateHarmonics) {
  75377. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75378. _this.sphericalPolynomial = sphericalPolynomial;
  75379. }
  75380. var results = [];
  75381. var byteArray = null;
  75382. // Push each faces.
  75383. for (var j = 0; j < 6; j++) {
  75384. // Create uintarray fallback.
  75385. if (!scene.getEngine().getCaps().textureFloat) {
  75386. // 3 channels of 1 bytes per pixel in bytes.
  75387. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75388. byteArray = new Uint8Array(byteBuffer);
  75389. }
  75390. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75391. // If special cases.
  75392. if (_this._useInGammaSpace || byteArray) {
  75393. for (var i = 0; i < _this._size * _this._size; i++) {
  75394. // Put in gamma space if requested.
  75395. if (_this._useInGammaSpace) {
  75396. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75397. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75398. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75399. }
  75400. // Convert to int texture for fallback.
  75401. if (byteArray) {
  75402. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75403. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75404. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75405. // May use luminance instead if the result is not accurate.
  75406. var max = Math.max(Math.max(r, g), b);
  75407. if (max > 255) {
  75408. var scale = 255 / max;
  75409. r *= scale;
  75410. g *= scale;
  75411. b *= scale;
  75412. }
  75413. byteArray[(i * 3) + 0] = r;
  75414. byteArray[(i * 3) + 1] = g;
  75415. byteArray[(i * 3) + 2] = b;
  75416. }
  75417. }
  75418. }
  75419. if (byteArray) {
  75420. results.push(byteArray);
  75421. }
  75422. else {
  75423. results.push(dataFace);
  75424. }
  75425. }
  75426. return results;
  75427. };
  75428. var mipmapGenerator = null;
  75429. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75430. // if (!this._noMipmap &&
  75431. // this._usePMREMGenerator) {
  75432. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75433. // // Custom setup of the generator matching with the PBR shader values.
  75434. // var generator = new BABYLON.PMREMGenerator(data,
  75435. // this._size,
  75436. // this._size,
  75437. // 0,
  75438. // 3,
  75439. // this.getScene().getEngine().getCaps().textureFloat,
  75440. // 2048,
  75441. // 0.25,
  75442. // false,
  75443. // true);
  75444. // return generator.filterCubeMap();
  75445. // };
  75446. // }
  75447. var scene = this.getScene();
  75448. if (scene) {
  75449. 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);
  75450. }
  75451. };
  75452. /**
  75453. * Starts the loading process of the texture.
  75454. */
  75455. HDRCubeTexture.prototype.loadTexture = function () {
  75456. if (this._isBABYLONPreprocessed) {
  75457. this.loadBabylonTexture();
  75458. }
  75459. else {
  75460. this.loadHDRTexture();
  75461. }
  75462. };
  75463. HDRCubeTexture.prototype.clone = function () {
  75464. var scene = this.getScene();
  75465. if (!scene) {
  75466. return this;
  75467. }
  75468. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75469. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75470. // Base texture
  75471. newTexture.level = this.level;
  75472. newTexture.wrapU = this.wrapU;
  75473. newTexture.wrapV = this.wrapV;
  75474. newTexture.coordinatesIndex = this.coordinatesIndex;
  75475. newTexture.coordinatesMode = this.coordinatesMode;
  75476. return newTexture;
  75477. };
  75478. // Methods
  75479. HDRCubeTexture.prototype.delayLoad = function () {
  75480. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75481. return;
  75482. }
  75483. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75484. this._texture = this._getFromCache(this.url, this._noMipmap);
  75485. if (!this._texture) {
  75486. this.loadTexture();
  75487. }
  75488. };
  75489. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75490. return this._textureMatrix;
  75491. };
  75492. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75493. this._textureMatrix = value;
  75494. };
  75495. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75496. var texture = null;
  75497. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75498. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75499. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75500. texture.name = parsedTexture.name;
  75501. texture.hasAlpha = parsedTexture.hasAlpha;
  75502. texture.level = parsedTexture.level;
  75503. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75504. texture.isBlocking = parsedTexture.isBlocking;
  75505. }
  75506. if (texture) {
  75507. if (parsedTexture.boundingBoxPosition) {
  75508. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75509. }
  75510. if (parsedTexture.boundingBoxSize) {
  75511. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75512. }
  75513. }
  75514. return texture;
  75515. };
  75516. HDRCubeTexture.prototype.serialize = function () {
  75517. if (!this.name) {
  75518. return null;
  75519. }
  75520. var serializationObject = {};
  75521. serializationObject.name = this.name;
  75522. serializationObject.hasAlpha = this.hasAlpha;
  75523. serializationObject.isCube = true;
  75524. serializationObject.level = this.level;
  75525. serializationObject.size = this._size;
  75526. serializationObject.coordinatesMode = this.coordinatesMode;
  75527. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75528. serializationObject.generateHarmonics = this._generateHarmonics;
  75529. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75530. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75531. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75532. serializationObject.noMipmap = this._noMipmap;
  75533. serializationObject.isBlocking = this._isBlocking;
  75534. return serializationObject;
  75535. };
  75536. /**
  75537. * Saves as a file the data contained in the texture in a binary format.
  75538. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75539. * as the spherical used in the lighting.
  75540. * @param url The HDR file url.
  75541. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75542. * @param onError Method called if any error happens during download.
  75543. * @return The packed binary data.
  75544. */
  75545. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75546. if (onError === void 0) { onError = null; }
  75547. var callback = function (buffer) {
  75548. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75549. // Returns a URL you can use as a href.
  75550. var objUrl = window.URL.createObjectURL(data);
  75551. // Simulates a link to it and click to dowload.
  75552. var a = document.createElement("a");
  75553. document.body.appendChild(a);
  75554. a.style.display = "none";
  75555. a.href = objUrl;
  75556. a.download = "envmap.babylon.hdr";
  75557. a.click();
  75558. };
  75559. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75560. };
  75561. /**
  75562. * Serializes the data contained in the texture in a binary format.
  75563. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75564. * as the spherical used in the lighting.
  75565. * @param url The HDR file url.
  75566. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75567. * @param onError Method called if any error happens during download.
  75568. * @return The packed binary data.
  75569. */
  75570. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75571. if (onError === void 0) { onError = null; }
  75572. // Needs the url tho create the texture.
  75573. if (!url) {
  75574. return;
  75575. }
  75576. // Check Power of two size.
  75577. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75578. return;
  75579. }
  75580. // Coming Back in 3.x.
  75581. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75582. };
  75583. HDRCubeTexture._facesMapping = [
  75584. "right",
  75585. "left",
  75586. "up",
  75587. "down",
  75588. "front",
  75589. "back"
  75590. ];
  75591. return HDRCubeTexture;
  75592. }(BABYLON.BaseTexture));
  75593. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75594. })(BABYLON || (BABYLON = {}));
  75595. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75596. "use strict";
  75597. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75598. // Huge respect for a such great lib.
  75599. // Earcut license:
  75600. // Copyright (c) 2016, Mapbox
  75601. //
  75602. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75603. // with or without fee is hereby granted, provided that the above copyright notice
  75604. // and this permission notice appear in all copies.
  75605. //
  75606. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75607. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75608. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75609. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75610. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75611. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75612. // THIS SOFTWARE.
  75613. var Earcut;
  75614. (function (Earcut) {
  75615. /**
  75616. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75617. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75618. * @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).
  75619. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75620. */
  75621. function earcut(data, holeIndices, dim) {
  75622. dim = dim || 2;
  75623. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75624. if (!outerNode)
  75625. return triangles;
  75626. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75627. if (hasHoles)
  75628. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75629. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75630. if (data.length > 80 * dim) {
  75631. minX = maxX = data[0];
  75632. minY = maxY = data[1];
  75633. for (var i = dim; i < outerLen; i += dim) {
  75634. x = data[i];
  75635. y = data[i + 1];
  75636. if (x < minX)
  75637. minX = x;
  75638. if (y < minY)
  75639. minY = y;
  75640. if (x > maxX)
  75641. maxX = x;
  75642. if (y > maxY)
  75643. maxY = y;
  75644. }
  75645. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75646. size = Math.max(maxX - minX, maxY - minY);
  75647. }
  75648. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75649. return triangles;
  75650. }
  75651. Earcut.earcut = earcut;
  75652. var Node = /** @class */ (function () {
  75653. function Node(i, x, y) {
  75654. this.i = i;
  75655. this.x = x;
  75656. this.y = y;
  75657. this.prev = null;
  75658. this.next = null;
  75659. this.z = null;
  75660. this.prevZ = null;
  75661. this.nextZ = null;
  75662. this.steiner = false;
  75663. }
  75664. return Node;
  75665. }());
  75666. // create a circular doubly linked list from polygon points in the specified winding order
  75667. function linkedList(data, start, end, dim, clockwise) {
  75668. var i, last = null;
  75669. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75670. for (i = start; i < end; i += dim)
  75671. last = insertNode(i, data[i], data[i + 1], last);
  75672. }
  75673. else {
  75674. for (i = end - dim; i >= start; i -= dim)
  75675. last = insertNode(i, data[i], data[i + 1], last);
  75676. }
  75677. if (last && equals(last, last.next)) {
  75678. removeNode(last);
  75679. last = last.next;
  75680. }
  75681. return last;
  75682. }
  75683. // eliminate colinear or duplicate points
  75684. function filterPoints(start, end) {
  75685. if (!start)
  75686. return start;
  75687. if (!end)
  75688. end = start;
  75689. var p = start, again;
  75690. do {
  75691. again = false;
  75692. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75693. removeNode(p);
  75694. p = end = p.prev;
  75695. if (p === p.next)
  75696. return undefined;
  75697. again = true;
  75698. }
  75699. else {
  75700. p = p.next;
  75701. }
  75702. } while (again || p !== end);
  75703. return end;
  75704. }
  75705. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75706. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75707. if (!ear)
  75708. return;
  75709. // interlink polygon nodes in z-order
  75710. if (!pass && size)
  75711. indexCurve(ear, minX, minY, size);
  75712. var stop = ear, prev, next;
  75713. // iterate through ears, slicing them one by one
  75714. while (ear.prev !== ear.next) {
  75715. prev = ear.prev;
  75716. next = ear.next;
  75717. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75718. // cut off the triangle
  75719. triangles.push(prev.i / dim);
  75720. triangles.push(ear.i / dim);
  75721. triangles.push(next.i / dim);
  75722. removeNode(ear);
  75723. // skipping the next vertice leads to less sliver triangles
  75724. ear = next.next;
  75725. stop = next.next;
  75726. continue;
  75727. }
  75728. ear = next;
  75729. // if we looped through the whole remaining polygon and can't find any more ears
  75730. if (ear === stop) {
  75731. // try filtering points and slicing again
  75732. if (!pass) {
  75733. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75734. // if this didn't work, try curing all small self-intersections locally
  75735. }
  75736. else if (pass === 1) {
  75737. ear = cureLocalIntersections(ear, triangles, dim);
  75738. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75739. // as a last resort, try splitting the remaining polygon into two
  75740. }
  75741. else if (pass === 2) {
  75742. splitEarcut(ear, triangles, dim, minX, minY, size);
  75743. }
  75744. break;
  75745. }
  75746. }
  75747. }
  75748. // check whether a polygon node forms a valid ear with adjacent nodes
  75749. function isEar(ear) {
  75750. var a = ear.prev, b = ear, c = ear.next;
  75751. if (area(a, b, c) >= 0)
  75752. return false; // reflex, can't be an ear
  75753. // now make sure we don't have other points inside the potential ear
  75754. var p = ear.next.next;
  75755. while (p !== ear.prev) {
  75756. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75757. area(p.prev, p, p.next) >= 0)
  75758. return false;
  75759. p = p.next;
  75760. }
  75761. return true;
  75762. }
  75763. function isEarHashed(ear, minX, minY, size) {
  75764. var a = ear.prev, b = ear, c = ear.next;
  75765. if (area(a, b, c) >= 0)
  75766. return false; // reflex, can't be an ear
  75767. // triangle bbox; min & max are calculated like this for speed
  75768. 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);
  75769. // z-order range for the current triangle bbox;
  75770. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75771. // first look for points inside the triangle in increasing z-order
  75772. var p = ear.nextZ;
  75773. while (p && p.z <= maxZ) {
  75774. if (p !== ear.prev &&
  75775. p !== ear.next &&
  75776. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75777. area(p.prev, p, p.next) >= 0)
  75778. return false;
  75779. p = p.nextZ;
  75780. }
  75781. // then look for points in decreasing z-order
  75782. p = ear.prevZ;
  75783. while (p && p.z >= minZ) {
  75784. if (p !== ear.prev &&
  75785. p !== ear.next &&
  75786. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75787. area(p.prev, p, p.next) >= 0)
  75788. return false;
  75789. p = p.prevZ;
  75790. }
  75791. return true;
  75792. }
  75793. // go through all polygon nodes and cure small local self-intersections
  75794. function cureLocalIntersections(start, triangles, dim) {
  75795. var p = start;
  75796. do {
  75797. var a = p.prev, b = p.next.next;
  75798. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75799. triangles.push(a.i / dim);
  75800. triangles.push(p.i / dim);
  75801. triangles.push(b.i / dim);
  75802. // remove two nodes involved
  75803. removeNode(p);
  75804. removeNode(p.next);
  75805. p = start = b;
  75806. }
  75807. p = p.next;
  75808. } while (p !== start);
  75809. return p;
  75810. }
  75811. // try splitting polygon into two and triangulate them independently
  75812. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75813. // look for a valid diagonal that divides the polygon into two
  75814. var a = start;
  75815. do {
  75816. var b = a.next.next;
  75817. while (b !== a.prev) {
  75818. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75819. // split the polygon in two by the diagonal
  75820. var c = splitPolygon(a, b);
  75821. // filter colinear points around the cuts
  75822. a = filterPoints(a, a.next);
  75823. c = filterPoints(c, c.next);
  75824. // run earcut on each half
  75825. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75826. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75827. return;
  75828. }
  75829. b = b.next;
  75830. }
  75831. a = a.next;
  75832. } while (a !== start);
  75833. }
  75834. // link every hole into the outer loop, producing a single-ring polygon without holes
  75835. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75836. var queue = [], i, len, start, end, list;
  75837. for (i = 0, len = holeIndices.length; i < len; i++) {
  75838. start = holeIndices[i] * dim;
  75839. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75840. list = linkedList(data, start, end, dim, false);
  75841. if (list === list.next)
  75842. list.steiner = true;
  75843. queue.push(getLeftmost(list));
  75844. }
  75845. queue.sort(compareX);
  75846. // process holes from left to right
  75847. for (i = 0; i < queue.length; i++) {
  75848. eliminateHole(queue[i], outerNode);
  75849. outerNode = filterPoints(outerNode, outerNode.next);
  75850. }
  75851. return outerNode;
  75852. }
  75853. function compareX(a, b) {
  75854. return a.x - b.x;
  75855. }
  75856. // find a bridge between vertices that connects hole with an outer ring and and link it
  75857. function eliminateHole(hole, outerNode) {
  75858. outerNode = findHoleBridge(hole, outerNode);
  75859. if (outerNode) {
  75860. var b = splitPolygon(outerNode, hole);
  75861. filterPoints(b, b.next);
  75862. }
  75863. }
  75864. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75865. function findHoleBridge(hole, outerNode) {
  75866. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75867. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75868. // segment's endpoint with lesser x will be potential connection point
  75869. do {
  75870. if (hy <= p.y && hy >= p.next.y) {
  75871. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75872. if (x <= hx && x > qx) {
  75873. qx = x;
  75874. if (x === hx) {
  75875. if (hy === p.y)
  75876. return p;
  75877. if (hy === p.next.y)
  75878. return p.next;
  75879. }
  75880. m = p.x < p.next.x ? p : p.next;
  75881. }
  75882. }
  75883. p = p.next;
  75884. } while (p !== outerNode);
  75885. if (!m)
  75886. return null;
  75887. if (hx === qx)
  75888. return m.prev; // hole touches outer segment; pick lower endpoint
  75889. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75890. // if there are no points found, we have a valid connection;
  75891. // otherwise choose the point of the minimum angle with the ray as connection point
  75892. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75893. p = m.next;
  75894. while (p !== stop) {
  75895. if (hx >= p.x &&
  75896. p.x >= mx &&
  75897. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75898. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75899. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75900. m = p;
  75901. tanMin = tan;
  75902. }
  75903. }
  75904. p = p.next;
  75905. }
  75906. return m;
  75907. }
  75908. // interlink polygon nodes in z-order
  75909. function indexCurve(start, minX, minY, size) {
  75910. var p = start;
  75911. do {
  75912. if (p.z === null)
  75913. p.z = zOrder(p.x, p.y, minX, minY, size);
  75914. p.prevZ = p.prev;
  75915. p.nextZ = p.next;
  75916. p = p.next;
  75917. } while (p !== start);
  75918. p.prevZ.nextZ = null;
  75919. p.prevZ = null;
  75920. sortLinked(p);
  75921. }
  75922. // Simon Tatham's linked list merge sort algorithm
  75923. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75924. function sortLinked(list) {
  75925. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75926. do {
  75927. p = list;
  75928. list = null;
  75929. tail = null;
  75930. numMerges = 0;
  75931. while (p) {
  75932. numMerges++;
  75933. q = p;
  75934. pSize = 0;
  75935. for (i = 0; i < inSize; i++) {
  75936. pSize++;
  75937. q = q.nextZ;
  75938. if (!q)
  75939. break;
  75940. }
  75941. qSize = inSize;
  75942. while (pSize > 0 || (qSize > 0 && q)) {
  75943. if (pSize === 0) {
  75944. e = q;
  75945. q = q.nextZ;
  75946. qSize--;
  75947. }
  75948. else if (qSize === 0 || !q) {
  75949. e = p;
  75950. p = p.nextZ;
  75951. pSize--;
  75952. }
  75953. else if (p.z <= q.z) {
  75954. e = p;
  75955. p = p.nextZ;
  75956. pSize--;
  75957. }
  75958. else {
  75959. e = q;
  75960. q = q.nextZ;
  75961. qSize--;
  75962. }
  75963. if (tail)
  75964. tail.nextZ = e;
  75965. else
  75966. list = e;
  75967. e.prevZ = tail;
  75968. tail = e;
  75969. }
  75970. p = q;
  75971. }
  75972. tail.nextZ = null;
  75973. inSize *= 2;
  75974. } while (numMerges > 1);
  75975. return list;
  75976. }
  75977. // z-order of a point given coords and size of the data bounding box
  75978. function zOrder(x, y, minX, minY, size) {
  75979. // coords are transformed into non-negative 15-bit integer range
  75980. x = 32767 * (x - minX) / size;
  75981. y = 32767 * (y - minY) / size;
  75982. x = (x | (x << 8)) & 0x00FF00FF;
  75983. x = (x | (x << 4)) & 0x0F0F0F0F;
  75984. x = (x | (x << 2)) & 0x33333333;
  75985. x = (x | (x << 1)) & 0x55555555;
  75986. y = (y | (y << 8)) & 0x00FF00FF;
  75987. y = (y | (y << 4)) & 0x0F0F0F0F;
  75988. y = (y | (y << 2)) & 0x33333333;
  75989. y = (y | (y << 1)) & 0x55555555;
  75990. return x | (y << 1);
  75991. }
  75992. // find the leftmost node of a polygon ring
  75993. function getLeftmost(start) {
  75994. var p = start, leftmost = start;
  75995. do {
  75996. if (p.x < leftmost.x)
  75997. leftmost = p;
  75998. p = p.next;
  75999. } while (p !== start);
  76000. return leftmost;
  76001. }
  76002. // check if a point lies within a convex triangle
  76003. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  76004. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  76005. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  76006. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  76007. }
  76008. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  76009. function isValidDiagonal(a, b) {
  76010. return a.next.i !== b.i &&
  76011. a.prev.i !== b.i &&
  76012. !intersectsPolygon(a, b) &&
  76013. locallyInside(a, b) &&
  76014. locallyInside(b, a) &&
  76015. middleInside(a, b);
  76016. }
  76017. // signed area of a triangle
  76018. function area(p, q, r) {
  76019. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  76020. }
  76021. // check if two points are equal
  76022. function equals(p1, p2) {
  76023. return p1.x === p2.x && p1.y === p2.y;
  76024. }
  76025. // check if two segments intersect
  76026. function intersects(p1, q1, p2, q2) {
  76027. if ((equals(p1, q1) && equals(p2, q2)) ||
  76028. (equals(p1, q2) && equals(p2, q1)))
  76029. return true;
  76030. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  76031. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  76032. }
  76033. // check if a polygon diagonal intersects any polygon segments
  76034. function intersectsPolygon(a, b) {
  76035. var p = a;
  76036. do {
  76037. if (p.i !== a.i &&
  76038. p.next.i !== a.i &&
  76039. p.i !== b.i &&
  76040. p.next.i !== b.i &&
  76041. intersects(p, p.next, a, b))
  76042. return true;
  76043. p = p.next;
  76044. } while (p !== a);
  76045. return false;
  76046. }
  76047. // check if a polygon diagonal is locally inside the polygon
  76048. function locallyInside(a, b) {
  76049. return area(a.prev, a, a.next) < 0
  76050. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  76051. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  76052. }
  76053. // check if the middle point of a polygon diagonal is inside the polygon
  76054. function middleInside(a, b) {
  76055. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  76056. do {
  76057. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  76058. inside = !inside;
  76059. p = p.next;
  76060. } while (p !== a);
  76061. return inside;
  76062. }
  76063. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  76064. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  76065. function splitPolygon(a, b) {
  76066. 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;
  76067. a.next = b;
  76068. b.prev = a;
  76069. a2.next = an;
  76070. an.prev = a2;
  76071. b2.next = a2;
  76072. a2.prev = b2;
  76073. bp.next = b2;
  76074. b2.prev = bp;
  76075. return b2;
  76076. }
  76077. // create a node and optionally link it with previous one (in a circular doubly linked list)
  76078. function insertNode(i, x, y, last) {
  76079. var p = new Node(i, x, y);
  76080. if (!last) {
  76081. p.prev = p;
  76082. p.next = p;
  76083. }
  76084. else {
  76085. p.next = last.next;
  76086. p.prev = last;
  76087. last.next.prev = p;
  76088. last.next = p;
  76089. }
  76090. return p;
  76091. }
  76092. function removeNode(p) {
  76093. p.next.prev = p.prev;
  76094. p.prev.next = p.next;
  76095. if (p.prevZ)
  76096. p.prevZ.nextZ = p.nextZ;
  76097. if (p.nextZ)
  76098. p.nextZ.prevZ = p.prevZ;
  76099. }
  76100. /**
  76101. * return a percentage difference between the polygon area and its triangulation area;
  76102. * used to verify correctness of triangulation
  76103. */
  76104. function deviation(data, holeIndices, dim, triangles) {
  76105. var hasHoles = holeIndices && holeIndices.length;
  76106. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  76107. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  76108. if (hasHoles) {
  76109. for (var i = 0, len = holeIndices.length; i < len; i++) {
  76110. var start = holeIndices[i] * dim;
  76111. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  76112. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  76113. }
  76114. }
  76115. var trianglesArea = 0;
  76116. for (i = 0; i < triangles.length; i += 3) {
  76117. var a = triangles[i] * dim;
  76118. var b = triangles[i + 1] * dim;
  76119. var c = triangles[i + 2] * dim;
  76120. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  76121. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  76122. }
  76123. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  76124. }
  76125. Earcut.deviation = deviation;
  76126. ;
  76127. function signedArea(data, start, end, dim) {
  76128. var sum = 0;
  76129. for (var i = start, j = end - dim; i < end; i += dim) {
  76130. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  76131. j = i;
  76132. }
  76133. return sum;
  76134. }
  76135. /**
  76136. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  76137. */
  76138. function flatten(data) {
  76139. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  76140. for (var i = 0; i < data.length; i++) {
  76141. for (var j = 0; j < data[i].length; j++) {
  76142. for (var d = 0; d < dim; d++)
  76143. result.vertices.push(data[i][j][d]);
  76144. }
  76145. if (i > 0) {
  76146. holeIndex += data[i - 1].length;
  76147. result.holes.push(holeIndex);
  76148. }
  76149. }
  76150. return result;
  76151. }
  76152. Earcut.flatten = flatten;
  76153. ;
  76154. })(Earcut || (Earcut = {}));
  76155. //# sourceMappingURL=babylon.earcut.js.map
  76156. "use strict";
  76157. var BABYLON;
  76158. (function (BABYLON) {
  76159. var IndexedVector2 = /** @class */ (function (_super) {
  76160. __extends(IndexedVector2, _super);
  76161. function IndexedVector2(original, index) {
  76162. var _this = _super.call(this, original.x, original.y) || this;
  76163. _this.index = index;
  76164. return _this;
  76165. }
  76166. return IndexedVector2;
  76167. }(BABYLON.Vector2));
  76168. var PolygonPoints = /** @class */ (function () {
  76169. function PolygonPoints() {
  76170. this.elements = new Array();
  76171. }
  76172. PolygonPoints.prototype.add = function (originalPoints) {
  76173. var _this = this;
  76174. var result = new Array();
  76175. originalPoints.forEach(function (point) {
  76176. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  76177. var newPoint = new IndexedVector2(point, _this.elements.length);
  76178. result.push(newPoint);
  76179. _this.elements.push(newPoint);
  76180. }
  76181. });
  76182. return result;
  76183. };
  76184. PolygonPoints.prototype.computeBounds = function () {
  76185. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76186. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76187. this.elements.forEach(function (point) {
  76188. // x
  76189. if (point.x < lmin.x) {
  76190. lmin.x = point.x;
  76191. }
  76192. else if (point.x > lmax.x) {
  76193. lmax.x = point.x;
  76194. }
  76195. // y
  76196. if (point.y < lmin.y) {
  76197. lmin.y = point.y;
  76198. }
  76199. else if (point.y > lmax.y) {
  76200. lmax.y = point.y;
  76201. }
  76202. });
  76203. return {
  76204. min: lmin,
  76205. max: lmax,
  76206. width: lmax.x - lmin.x,
  76207. height: lmax.y - lmin.y
  76208. };
  76209. };
  76210. return PolygonPoints;
  76211. }());
  76212. var Polygon = /** @class */ (function () {
  76213. function Polygon() {
  76214. }
  76215. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  76216. return [
  76217. new BABYLON.Vector2(xmin, ymin),
  76218. new BABYLON.Vector2(xmax, ymin),
  76219. new BABYLON.Vector2(xmax, ymax),
  76220. new BABYLON.Vector2(xmin, ymax)
  76221. ];
  76222. };
  76223. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  76224. if (cx === void 0) { cx = 0; }
  76225. if (cy === void 0) { cy = 0; }
  76226. if (numberOfSides === void 0) { numberOfSides = 32; }
  76227. var result = new Array();
  76228. var angle = 0;
  76229. var increment = (Math.PI * 2) / numberOfSides;
  76230. for (var i = 0; i < numberOfSides; i++) {
  76231. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  76232. angle -= increment;
  76233. }
  76234. return result;
  76235. };
  76236. Polygon.Parse = function (input) {
  76237. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  76238. var i, result = [];
  76239. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  76240. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  76241. }
  76242. return result;
  76243. };
  76244. Polygon.StartingAt = function (x, y) {
  76245. return BABYLON.Path2.StartingAt(x, y);
  76246. };
  76247. return Polygon;
  76248. }());
  76249. BABYLON.Polygon = Polygon;
  76250. var PolygonMeshBuilder = /** @class */ (function () {
  76251. function PolygonMeshBuilder(name, contours, scene) {
  76252. this._points = new PolygonPoints();
  76253. this._outlinepoints = new PolygonPoints();
  76254. this._holes = new Array();
  76255. this._epoints = new Array();
  76256. this._eholes = new Array();
  76257. this._name = name;
  76258. this._scene = scene;
  76259. var points;
  76260. if (contours instanceof BABYLON.Path2) {
  76261. points = contours.getPoints();
  76262. }
  76263. else {
  76264. points = contours;
  76265. }
  76266. this._addToepoint(points);
  76267. this._points.add(points);
  76268. this._outlinepoints.add(points);
  76269. }
  76270. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  76271. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  76272. var p = points_1[_i];
  76273. this._epoints.push(p.x, p.y);
  76274. }
  76275. };
  76276. PolygonMeshBuilder.prototype.addHole = function (hole) {
  76277. this._points.add(hole);
  76278. var holepoints = new PolygonPoints();
  76279. holepoints.add(hole);
  76280. this._holes.push(holepoints);
  76281. this._eholes.push(this._epoints.length / 2);
  76282. this._addToepoint(hole);
  76283. return this;
  76284. };
  76285. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  76286. var _this = this;
  76287. if (updatable === void 0) { updatable = false; }
  76288. if (depth === void 0) { depth = 0; }
  76289. var result = new BABYLON.Mesh(this._name, this._scene);
  76290. var normals = new Array();
  76291. var positions = new Array();
  76292. var uvs = new Array();
  76293. var bounds = this._points.computeBounds();
  76294. this._points.elements.forEach(function (p) {
  76295. normals.push(0, 1.0, 0);
  76296. positions.push(p.x, 0, p.y);
  76297. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  76298. });
  76299. var indices = new Array();
  76300. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  76301. for (var i = 0; i < res.length; i++) {
  76302. indices.push(res[i]);
  76303. }
  76304. if (depth > 0) {
  76305. var positionscount = (positions.length / 3); //get the current pointcount
  76306. this._points.elements.forEach(function (p) {
  76307. normals.push(0, -1.0, 0);
  76308. positions.push(p.x, -depth, p.y);
  76309. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76310. });
  76311. var totalCount = indices.length;
  76312. for (var i = 0; i < totalCount; i += 3) {
  76313. var i0 = indices[i + 0];
  76314. var i1 = indices[i + 1];
  76315. var i2 = indices[i + 2];
  76316. indices.push(i2 + positionscount);
  76317. indices.push(i1 + positionscount);
  76318. indices.push(i0 + positionscount);
  76319. }
  76320. //Add the sides
  76321. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76322. this._holes.forEach(function (hole) {
  76323. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76324. });
  76325. }
  76326. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76327. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76328. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76329. result.setIndices(indices);
  76330. return result;
  76331. };
  76332. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76333. var StartIndex = positions.length / 3;
  76334. var ulength = 0;
  76335. for (var i = 0; i < points.elements.length; i++) {
  76336. var p = points.elements[i];
  76337. var p1;
  76338. if ((i + 1) > points.elements.length - 1) {
  76339. p1 = points.elements[0];
  76340. }
  76341. else {
  76342. p1 = points.elements[i + 1];
  76343. }
  76344. positions.push(p.x, 0, p.y);
  76345. positions.push(p.x, -depth, p.y);
  76346. positions.push(p1.x, 0, p1.y);
  76347. positions.push(p1.x, -depth, p1.y);
  76348. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76349. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76350. var v3 = v2.subtract(v1);
  76351. var v4 = new BABYLON.Vector3(0, 1, 0);
  76352. var vn = BABYLON.Vector3.Cross(v3, v4);
  76353. vn = vn.normalize();
  76354. uvs.push(ulength / bounds.width, 0);
  76355. uvs.push(ulength / bounds.width, 1);
  76356. ulength += v3.length();
  76357. uvs.push((ulength / bounds.width), 0);
  76358. uvs.push((ulength / bounds.width), 1);
  76359. if (!flip) {
  76360. normals.push(-vn.x, -vn.y, -vn.z);
  76361. normals.push(-vn.x, -vn.y, -vn.z);
  76362. normals.push(-vn.x, -vn.y, -vn.z);
  76363. normals.push(-vn.x, -vn.y, -vn.z);
  76364. indices.push(StartIndex);
  76365. indices.push(StartIndex + 1);
  76366. indices.push(StartIndex + 2);
  76367. indices.push(StartIndex + 1);
  76368. indices.push(StartIndex + 3);
  76369. indices.push(StartIndex + 2);
  76370. }
  76371. else {
  76372. normals.push(vn.x, vn.y, vn.z);
  76373. normals.push(vn.x, vn.y, vn.z);
  76374. normals.push(vn.x, vn.y, vn.z);
  76375. normals.push(vn.x, vn.y, vn.z);
  76376. indices.push(StartIndex);
  76377. indices.push(StartIndex + 2);
  76378. indices.push(StartIndex + 1);
  76379. indices.push(StartIndex + 1);
  76380. indices.push(StartIndex + 2);
  76381. indices.push(StartIndex + 3);
  76382. }
  76383. StartIndex += 4;
  76384. }
  76385. ;
  76386. };
  76387. return PolygonMeshBuilder;
  76388. }());
  76389. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76390. })(BABYLON || (BABYLON = {}));
  76391. //# sourceMappingURL=babylon.polygonMesh.js.map
  76392. "use strict";
  76393. var BABYLON;
  76394. (function (BABYLON) {
  76395. // Unique ID when we import meshes from Babylon to CSG
  76396. var currentCSGMeshId = 0;
  76397. // # class Vertex
  76398. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76399. // one to provide additional features like texture coordinates and vertex
  76400. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76401. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76402. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76403. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76404. // is not used anywhere else.
  76405. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76406. var Vertex = /** @class */ (function () {
  76407. function Vertex(pos, normal, uv) {
  76408. this.pos = pos;
  76409. this.normal = normal;
  76410. this.uv = uv;
  76411. }
  76412. Vertex.prototype.clone = function () {
  76413. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76414. };
  76415. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76416. // orientation of a polygon is flipped.
  76417. Vertex.prototype.flip = function () {
  76418. this.normal = this.normal.scale(-1);
  76419. };
  76420. // Create a new vertex between this vertex and `other` by linearly
  76421. // interpolating all properties using a parameter of `t`. Subclasses should
  76422. // override this to interpolate additional properties.
  76423. Vertex.prototype.interpolate = function (other, t) {
  76424. 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));
  76425. };
  76426. return Vertex;
  76427. }());
  76428. // # class Plane
  76429. // Represents a plane in 3D space.
  76430. var Plane = /** @class */ (function () {
  76431. function Plane(normal, w) {
  76432. this.normal = normal;
  76433. this.w = w;
  76434. }
  76435. Plane.FromPoints = function (a, b, c) {
  76436. var v0 = c.subtract(a);
  76437. var v1 = b.subtract(a);
  76438. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76439. return null;
  76440. }
  76441. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76442. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76443. };
  76444. Plane.prototype.clone = function () {
  76445. return new Plane(this.normal.clone(), this.w);
  76446. };
  76447. Plane.prototype.flip = function () {
  76448. this.normal.scaleInPlace(-1);
  76449. this.w = -this.w;
  76450. };
  76451. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76452. // fragments in the appropriate lists. Coplanar polygons go into either
  76453. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76454. // respect to this plane. Polygons in front or in back of this plane go into
  76455. // either `front` or `back`.
  76456. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76457. var COPLANAR = 0;
  76458. var FRONT = 1;
  76459. var BACK = 2;
  76460. var SPANNING = 3;
  76461. // Classify each point as well as the entire polygon into one of the above
  76462. // four classes.
  76463. var polygonType = 0;
  76464. var types = [];
  76465. var i;
  76466. var t;
  76467. for (i = 0; i < polygon.vertices.length; i++) {
  76468. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76469. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76470. polygonType |= type;
  76471. types.push(type);
  76472. }
  76473. // Put the polygon in the correct list, splitting it when necessary.
  76474. switch (polygonType) {
  76475. case COPLANAR:
  76476. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76477. break;
  76478. case FRONT:
  76479. front.push(polygon);
  76480. break;
  76481. case BACK:
  76482. back.push(polygon);
  76483. break;
  76484. case SPANNING:
  76485. var f = [], b = [];
  76486. for (i = 0; i < polygon.vertices.length; i++) {
  76487. var j = (i + 1) % polygon.vertices.length;
  76488. var ti = types[i], tj = types[j];
  76489. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76490. if (ti !== BACK)
  76491. f.push(vi);
  76492. if (ti !== FRONT)
  76493. b.push(ti !== BACK ? vi.clone() : vi);
  76494. if ((ti | tj) === SPANNING) {
  76495. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76496. var v = vi.interpolate(vj, t);
  76497. f.push(v);
  76498. b.push(v.clone());
  76499. }
  76500. }
  76501. var poly;
  76502. if (f.length >= 3) {
  76503. poly = new Polygon(f, polygon.shared);
  76504. if (poly.plane)
  76505. front.push(poly);
  76506. }
  76507. if (b.length >= 3) {
  76508. poly = new Polygon(b, polygon.shared);
  76509. if (poly.plane)
  76510. back.push(poly);
  76511. }
  76512. break;
  76513. }
  76514. };
  76515. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76516. // point is on the plane.
  76517. Plane.EPSILON = 1e-5;
  76518. return Plane;
  76519. }());
  76520. // # class Polygon
  76521. // Represents a convex polygon. The vertices used to initialize a polygon must
  76522. // be coplanar and form a convex loop.
  76523. //
  76524. // Each convex polygon has a `shared` property, which is shared between all
  76525. // polygons that are clones of each other or were split from the same polygon.
  76526. // This can be used to define per-polygon properties (such as surface color).
  76527. var Polygon = /** @class */ (function () {
  76528. function Polygon(vertices, shared) {
  76529. this.vertices = vertices;
  76530. this.shared = shared;
  76531. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76532. }
  76533. Polygon.prototype.clone = function () {
  76534. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76535. return new Polygon(vertices, this.shared);
  76536. };
  76537. Polygon.prototype.flip = function () {
  76538. this.vertices.reverse().map(function (v) { v.flip(); });
  76539. this.plane.flip();
  76540. };
  76541. return Polygon;
  76542. }());
  76543. // # class Node
  76544. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76545. // by picking a polygon to split along. That polygon (and all other coplanar
  76546. // polygons) are added directly to that node and the other polygons are added to
  76547. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76548. // no distinction between internal and leaf nodes.
  76549. var Node = /** @class */ (function () {
  76550. function Node(polygons) {
  76551. this.plane = null;
  76552. this.front = null;
  76553. this.back = null;
  76554. this.polygons = new Array();
  76555. if (polygons) {
  76556. this.build(polygons);
  76557. }
  76558. }
  76559. Node.prototype.clone = function () {
  76560. var node = new Node();
  76561. node.plane = this.plane && this.plane.clone();
  76562. node.front = this.front && this.front.clone();
  76563. node.back = this.back && this.back.clone();
  76564. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76565. return node;
  76566. };
  76567. // Convert solid space to empty space and empty space to solid space.
  76568. Node.prototype.invert = function () {
  76569. for (var i = 0; i < this.polygons.length; i++) {
  76570. this.polygons[i].flip();
  76571. }
  76572. if (this.plane) {
  76573. this.plane.flip();
  76574. }
  76575. if (this.front) {
  76576. this.front.invert();
  76577. }
  76578. if (this.back) {
  76579. this.back.invert();
  76580. }
  76581. var temp = this.front;
  76582. this.front = this.back;
  76583. this.back = temp;
  76584. };
  76585. // Recursively remove all polygons in `polygons` that are inside this BSP
  76586. // tree.
  76587. Node.prototype.clipPolygons = function (polygons) {
  76588. if (!this.plane)
  76589. return polygons.slice();
  76590. var front = new Array(), back = new Array();
  76591. for (var i = 0; i < polygons.length; i++) {
  76592. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76593. }
  76594. if (this.front) {
  76595. front = this.front.clipPolygons(front);
  76596. }
  76597. if (this.back) {
  76598. back = this.back.clipPolygons(back);
  76599. }
  76600. else {
  76601. back = [];
  76602. }
  76603. return front.concat(back);
  76604. };
  76605. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76606. // `bsp`.
  76607. Node.prototype.clipTo = function (bsp) {
  76608. this.polygons = bsp.clipPolygons(this.polygons);
  76609. if (this.front)
  76610. this.front.clipTo(bsp);
  76611. if (this.back)
  76612. this.back.clipTo(bsp);
  76613. };
  76614. // Return a list of all polygons in this BSP tree.
  76615. Node.prototype.allPolygons = function () {
  76616. var polygons = this.polygons.slice();
  76617. if (this.front)
  76618. polygons = polygons.concat(this.front.allPolygons());
  76619. if (this.back)
  76620. polygons = polygons.concat(this.back.allPolygons());
  76621. return polygons;
  76622. };
  76623. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76624. // new polygons are filtered down to the bottom of the tree and become new
  76625. // nodes there. Each set of polygons is partitioned using the first polygon
  76626. // (no heuristic is used to pick a good split).
  76627. Node.prototype.build = function (polygons) {
  76628. if (!polygons.length)
  76629. return;
  76630. if (!this.plane)
  76631. this.plane = polygons[0].plane.clone();
  76632. var front = new Array(), back = new Array();
  76633. for (var i = 0; i < polygons.length; i++) {
  76634. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76635. }
  76636. if (front.length) {
  76637. if (!this.front)
  76638. this.front = new Node();
  76639. this.front.build(front);
  76640. }
  76641. if (back.length) {
  76642. if (!this.back)
  76643. this.back = new Node();
  76644. this.back.build(back);
  76645. }
  76646. };
  76647. return Node;
  76648. }());
  76649. var CSG = /** @class */ (function () {
  76650. function CSG() {
  76651. this.polygons = new Array();
  76652. }
  76653. // Convert BABYLON.Mesh to BABYLON.CSG
  76654. CSG.FromMesh = function (mesh) {
  76655. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76656. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76657. if (mesh instanceof BABYLON.Mesh) {
  76658. mesh.computeWorldMatrix(true);
  76659. matrix = mesh.getWorldMatrix();
  76660. meshPosition = mesh.position.clone();
  76661. meshRotation = mesh.rotation.clone();
  76662. if (mesh.rotationQuaternion) {
  76663. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76664. }
  76665. meshScaling = mesh.scaling.clone();
  76666. }
  76667. else {
  76668. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76669. }
  76670. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76671. var subMeshes = mesh.subMeshes;
  76672. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76673. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76674. vertices = [];
  76675. for (var j = 0; j < 3; j++) {
  76676. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76677. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76678. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76679. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76680. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76681. vertex = new Vertex(position, normal, uv);
  76682. vertices.push(vertex);
  76683. }
  76684. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76685. // To handle the case of degenerated triangle
  76686. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76687. if (polygon.plane)
  76688. polygons.push(polygon);
  76689. }
  76690. }
  76691. var csg = CSG.FromPolygons(polygons);
  76692. csg.matrix = matrix;
  76693. csg.position = meshPosition;
  76694. csg.rotation = meshRotation;
  76695. csg.scaling = meshScaling;
  76696. csg.rotationQuaternion = meshRotationQuaternion;
  76697. currentCSGMeshId++;
  76698. return csg;
  76699. };
  76700. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76701. CSG.FromPolygons = function (polygons) {
  76702. var csg = new CSG();
  76703. csg.polygons = polygons;
  76704. return csg;
  76705. };
  76706. CSG.prototype.clone = function () {
  76707. var csg = new CSG();
  76708. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76709. csg.copyTransformAttributes(this);
  76710. return csg;
  76711. };
  76712. CSG.prototype.union = function (csg) {
  76713. var a = new Node(this.clone().polygons);
  76714. var b = new Node(csg.clone().polygons);
  76715. a.clipTo(b);
  76716. b.clipTo(a);
  76717. b.invert();
  76718. b.clipTo(a);
  76719. b.invert();
  76720. a.build(b.allPolygons());
  76721. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76722. };
  76723. CSG.prototype.unionInPlace = function (csg) {
  76724. var a = new Node(this.polygons);
  76725. var b = new Node(csg.polygons);
  76726. a.clipTo(b);
  76727. b.clipTo(a);
  76728. b.invert();
  76729. b.clipTo(a);
  76730. b.invert();
  76731. a.build(b.allPolygons());
  76732. this.polygons = a.allPolygons();
  76733. };
  76734. CSG.prototype.subtract = function (csg) {
  76735. var a = new Node(this.clone().polygons);
  76736. var b = new Node(csg.clone().polygons);
  76737. a.invert();
  76738. a.clipTo(b);
  76739. b.clipTo(a);
  76740. b.invert();
  76741. b.clipTo(a);
  76742. b.invert();
  76743. a.build(b.allPolygons());
  76744. a.invert();
  76745. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76746. };
  76747. CSG.prototype.subtractInPlace = function (csg) {
  76748. var a = new Node(this.polygons);
  76749. var b = new Node(csg.polygons);
  76750. a.invert();
  76751. a.clipTo(b);
  76752. b.clipTo(a);
  76753. b.invert();
  76754. b.clipTo(a);
  76755. b.invert();
  76756. a.build(b.allPolygons());
  76757. a.invert();
  76758. this.polygons = a.allPolygons();
  76759. };
  76760. CSG.prototype.intersect = function (csg) {
  76761. var a = new Node(this.clone().polygons);
  76762. var b = new Node(csg.clone().polygons);
  76763. a.invert();
  76764. b.clipTo(a);
  76765. b.invert();
  76766. a.clipTo(b);
  76767. b.clipTo(a);
  76768. a.build(b.allPolygons());
  76769. a.invert();
  76770. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76771. };
  76772. CSG.prototype.intersectInPlace = function (csg) {
  76773. var a = new Node(this.polygons);
  76774. var b = new Node(csg.polygons);
  76775. a.invert();
  76776. b.clipTo(a);
  76777. b.invert();
  76778. a.clipTo(b);
  76779. b.clipTo(a);
  76780. a.build(b.allPolygons());
  76781. a.invert();
  76782. this.polygons = a.allPolygons();
  76783. };
  76784. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76785. // not modified.
  76786. CSG.prototype.inverse = function () {
  76787. var csg = this.clone();
  76788. csg.inverseInPlace();
  76789. return csg;
  76790. };
  76791. CSG.prototype.inverseInPlace = function () {
  76792. this.polygons.map(function (p) { p.flip(); });
  76793. };
  76794. // This is used to keep meshes transformations so they can be restored
  76795. // when we build back a Babylon Mesh
  76796. // NB : All CSG operations are performed in world coordinates
  76797. CSG.prototype.copyTransformAttributes = function (csg) {
  76798. this.matrix = csg.matrix;
  76799. this.position = csg.position;
  76800. this.rotation = csg.rotation;
  76801. this.scaling = csg.scaling;
  76802. this.rotationQuaternion = csg.rotationQuaternion;
  76803. return this;
  76804. };
  76805. // Build Raw mesh from CSG
  76806. // Coordinates here are in world space
  76807. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76808. var matrix = this.matrix.clone();
  76809. matrix.invert();
  76810. 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;
  76811. if (keepSubMeshes) {
  76812. // Sort Polygons, since subMeshes are indices range
  76813. polygons.sort(function (a, b) {
  76814. if (a.shared.meshId === b.shared.meshId) {
  76815. return a.shared.subMeshId - b.shared.subMeshId;
  76816. }
  76817. else {
  76818. return a.shared.meshId - b.shared.meshId;
  76819. }
  76820. });
  76821. }
  76822. for (var i = 0, il = polygons.length; i < il; i++) {
  76823. polygon = polygons[i];
  76824. // Building SubMeshes
  76825. if (!subMesh_dict[polygon.shared.meshId]) {
  76826. subMesh_dict[polygon.shared.meshId] = {};
  76827. }
  76828. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76829. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76830. indexStart: +Infinity,
  76831. indexEnd: -Infinity,
  76832. materialIndex: polygon.shared.materialIndex
  76833. };
  76834. }
  76835. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76836. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76837. polygonIndices[0] = 0;
  76838. polygonIndices[1] = j - 1;
  76839. polygonIndices[2] = j;
  76840. for (var k = 0; k < 3; k++) {
  76841. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76842. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76843. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76844. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76845. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76846. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76847. // Check if 2 points can be merged
  76848. if (!(typeof vertex_idx !== 'undefined' &&
  76849. normals[vertex_idx * 3] === localNormal.x &&
  76850. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76851. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76852. uvs[vertex_idx * 2] === uv.x &&
  76853. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76854. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76855. uvs.push(uv.x, uv.y);
  76856. normals.push(normal.x, normal.y, normal.z);
  76857. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76858. }
  76859. indices.push(vertex_idx);
  76860. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76861. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76862. currentIndex++;
  76863. }
  76864. }
  76865. }
  76866. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76867. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76868. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76869. mesh.setIndices(indices, null);
  76870. if (keepSubMeshes) {
  76871. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76872. var materialIndexOffset = 0, materialMaxIndex;
  76873. mesh.subMeshes = new Array();
  76874. for (var m in subMesh_dict) {
  76875. materialMaxIndex = -1;
  76876. for (var sm in subMesh_dict[m]) {
  76877. subMesh_obj = subMesh_dict[m][sm];
  76878. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76879. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76880. }
  76881. materialIndexOffset += ++materialMaxIndex;
  76882. }
  76883. }
  76884. return mesh;
  76885. };
  76886. // Build Mesh from CSG taking material and transforms into account
  76887. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76888. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76889. mesh.material = material;
  76890. mesh.position.copyFrom(this.position);
  76891. mesh.rotation.copyFrom(this.rotation);
  76892. if (this.rotationQuaternion) {
  76893. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76894. }
  76895. mesh.scaling.copyFrom(this.scaling);
  76896. mesh.computeWorldMatrix(true);
  76897. return mesh;
  76898. };
  76899. return CSG;
  76900. }());
  76901. BABYLON.CSG = CSG;
  76902. })(BABYLON || (BABYLON = {}));
  76903. //# sourceMappingURL=babylon.csg.js.map
  76904. "use strict";
  76905. var BABYLON;
  76906. (function (BABYLON) {
  76907. var LensFlare = /** @class */ (function () {
  76908. function LensFlare(size, position, color, imgUrl, system) {
  76909. this.size = size;
  76910. this.position = position;
  76911. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76912. this.color = color || new BABYLON.Color3(1, 1, 1);
  76913. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76914. this._system = system;
  76915. system.lensFlares.push(this);
  76916. }
  76917. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76918. return new LensFlare(size, position, color, imgUrl, system);
  76919. };
  76920. LensFlare.prototype.dispose = function () {
  76921. if (this.texture) {
  76922. this.texture.dispose();
  76923. }
  76924. // Remove from scene
  76925. var index = this._system.lensFlares.indexOf(this);
  76926. this._system.lensFlares.splice(index, 1);
  76927. };
  76928. ;
  76929. return LensFlare;
  76930. }());
  76931. BABYLON.LensFlare = LensFlare;
  76932. })(BABYLON || (BABYLON = {}));
  76933. //# sourceMappingURL=babylon.lensFlare.js.map
  76934. "use strict";
  76935. var BABYLON;
  76936. (function (BABYLON) {
  76937. var LensFlareSystem = /** @class */ (function () {
  76938. function LensFlareSystem(name, emitter, scene) {
  76939. this.name = name;
  76940. this.lensFlares = new Array();
  76941. this.borderLimit = 300;
  76942. this.viewportBorder = 0;
  76943. this.layerMask = 0x0FFFFFFF;
  76944. this._vertexBuffers = {};
  76945. this._isEnabled = true;
  76946. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76947. this._emitter = emitter;
  76948. this.id = name;
  76949. scene.lensFlareSystems.push(this);
  76950. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76951. var engine = scene.getEngine();
  76952. // VBO
  76953. var vertices = [];
  76954. vertices.push(1, 1);
  76955. vertices.push(-1, 1);
  76956. vertices.push(-1, -1);
  76957. vertices.push(1, -1);
  76958. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76959. // Indices
  76960. var indices = [];
  76961. indices.push(0);
  76962. indices.push(1);
  76963. indices.push(2);
  76964. indices.push(0);
  76965. indices.push(2);
  76966. indices.push(3);
  76967. this._indexBuffer = engine.createIndexBuffer(indices);
  76968. // Effects
  76969. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76970. }
  76971. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76972. get: function () {
  76973. return this._isEnabled;
  76974. },
  76975. set: function (value) {
  76976. this._isEnabled = value;
  76977. },
  76978. enumerable: true,
  76979. configurable: true
  76980. });
  76981. LensFlareSystem.prototype.getScene = function () {
  76982. return this._scene;
  76983. };
  76984. LensFlareSystem.prototype.getEmitter = function () {
  76985. return this._emitter;
  76986. };
  76987. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76988. this._emitter = newEmitter;
  76989. };
  76990. LensFlareSystem.prototype.getEmitterPosition = function () {
  76991. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76992. };
  76993. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76994. var position = this.getEmitterPosition();
  76995. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76996. this._positionX = position.x;
  76997. this._positionY = position.y;
  76998. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76999. if (this.viewportBorder > 0) {
  77000. globalViewport.x -= this.viewportBorder;
  77001. globalViewport.y -= this.viewportBorder;
  77002. globalViewport.width += this.viewportBorder * 2;
  77003. globalViewport.height += this.viewportBorder * 2;
  77004. position.x += this.viewportBorder;
  77005. position.y += this.viewportBorder;
  77006. this._positionX += this.viewportBorder;
  77007. this._positionY += this.viewportBorder;
  77008. }
  77009. if (position.z > 0) {
  77010. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  77011. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  77012. return true;
  77013. }
  77014. return true;
  77015. }
  77016. return false;
  77017. };
  77018. LensFlareSystem.prototype._isVisible = function () {
  77019. if (!this._isEnabled || !this._scene.activeCamera) {
  77020. return false;
  77021. }
  77022. var emitterPosition = this.getEmitterPosition();
  77023. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  77024. var distance = direction.length();
  77025. direction.normalize();
  77026. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  77027. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  77028. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  77029. };
  77030. LensFlareSystem.prototype.render = function () {
  77031. if (!this._effect.isReady() || !this._scene.activeCamera)
  77032. return false;
  77033. var engine = this._scene.getEngine();
  77034. var viewport = this._scene.activeCamera.viewport;
  77035. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  77036. // Position
  77037. if (!this.computeEffectivePosition(globalViewport)) {
  77038. return false;
  77039. }
  77040. // Visibility
  77041. if (!this._isVisible()) {
  77042. return false;
  77043. }
  77044. // Intensity
  77045. var awayX;
  77046. var awayY;
  77047. if (this._positionX < this.borderLimit + globalViewport.x) {
  77048. awayX = this.borderLimit + globalViewport.x - this._positionX;
  77049. }
  77050. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  77051. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  77052. }
  77053. else {
  77054. awayX = 0;
  77055. }
  77056. if (this._positionY < this.borderLimit + globalViewport.y) {
  77057. awayY = this.borderLimit + globalViewport.y - this._positionY;
  77058. }
  77059. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  77060. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  77061. }
  77062. else {
  77063. awayY = 0;
  77064. }
  77065. var away = (awayX > awayY) ? awayX : awayY;
  77066. away -= this.viewportBorder;
  77067. if (away > this.borderLimit) {
  77068. away = this.borderLimit;
  77069. }
  77070. var intensity = 1.0 - (away / this.borderLimit);
  77071. if (intensity < 0) {
  77072. return false;
  77073. }
  77074. if (intensity > 1.0) {
  77075. intensity = 1.0;
  77076. }
  77077. if (this.viewportBorder > 0) {
  77078. globalViewport.x += this.viewportBorder;
  77079. globalViewport.y += this.viewportBorder;
  77080. globalViewport.width -= this.viewportBorder * 2;
  77081. globalViewport.height -= this.viewportBorder * 2;
  77082. this._positionX -= this.viewportBorder;
  77083. this._positionY -= this.viewportBorder;
  77084. }
  77085. // Position
  77086. var centerX = globalViewport.x + globalViewport.width / 2;
  77087. var centerY = globalViewport.y + globalViewport.height / 2;
  77088. var distX = centerX - this._positionX;
  77089. var distY = centerY - this._positionY;
  77090. // Effects
  77091. engine.enableEffect(this._effect);
  77092. engine.setState(false);
  77093. engine.setDepthBuffer(false);
  77094. // VBOs
  77095. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77096. // Flares
  77097. for (var index = 0; index < this.lensFlares.length; index++) {
  77098. var flare = this.lensFlares[index];
  77099. engine.setAlphaMode(flare.alphaMode);
  77100. var x = centerX - (distX * flare.position);
  77101. var y = centerY - (distY * flare.position);
  77102. var cw = flare.size;
  77103. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  77104. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  77105. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  77106. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  77107. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  77108. // Texture
  77109. this._effect.setTexture("textureSampler", flare.texture);
  77110. // Color
  77111. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  77112. // Draw order
  77113. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77114. }
  77115. engine.setDepthBuffer(true);
  77116. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77117. return true;
  77118. };
  77119. LensFlareSystem.prototype.dispose = function () {
  77120. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77121. if (vertexBuffer) {
  77122. vertexBuffer.dispose();
  77123. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77124. }
  77125. if (this._indexBuffer) {
  77126. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77127. this._indexBuffer = null;
  77128. }
  77129. while (this.lensFlares.length) {
  77130. this.lensFlares[0].dispose();
  77131. }
  77132. // Remove from scene
  77133. var index = this._scene.lensFlareSystems.indexOf(this);
  77134. this._scene.lensFlareSystems.splice(index, 1);
  77135. };
  77136. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  77137. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  77138. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  77139. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  77140. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  77141. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  77142. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  77143. var parsedFlare = parsedLensFlareSystem.flares[index];
  77144. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  77145. }
  77146. return lensFlareSystem;
  77147. };
  77148. LensFlareSystem.prototype.serialize = function () {
  77149. var serializationObject = {};
  77150. serializationObject.id = this.id;
  77151. serializationObject.name = this.name;
  77152. serializationObject.emitterId = this.getEmitter().id;
  77153. serializationObject.borderLimit = this.borderLimit;
  77154. serializationObject.flares = [];
  77155. for (var index = 0; index < this.lensFlares.length; index++) {
  77156. var flare = this.lensFlares[index];
  77157. serializationObject.flares.push({
  77158. size: flare.size,
  77159. position: flare.position,
  77160. color: flare.color.asArray(),
  77161. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  77162. });
  77163. }
  77164. return serializationObject;
  77165. };
  77166. return LensFlareSystem;
  77167. }());
  77168. BABYLON.LensFlareSystem = LensFlareSystem;
  77169. })(BABYLON || (BABYLON = {}));
  77170. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  77171. "use strict";
  77172. var BABYLON;
  77173. (function (BABYLON) {
  77174. /**
  77175. * This is a holder class for the physics joint created by the physics plugin.
  77176. * It holds a set of functions to control the underlying joint.
  77177. */
  77178. var PhysicsJoint = /** @class */ (function () {
  77179. function PhysicsJoint(type, jointData) {
  77180. this.type = type;
  77181. this.jointData = jointData;
  77182. jointData.nativeParams = jointData.nativeParams || {};
  77183. }
  77184. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  77185. get: function () {
  77186. return this._physicsJoint;
  77187. },
  77188. set: function (newJoint) {
  77189. if (this._physicsJoint) {
  77190. //remove from the wolrd
  77191. }
  77192. this._physicsJoint = newJoint;
  77193. },
  77194. enumerable: true,
  77195. configurable: true
  77196. });
  77197. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  77198. set: function (physicsPlugin) {
  77199. this._physicsPlugin = physicsPlugin;
  77200. },
  77201. enumerable: true,
  77202. configurable: true
  77203. });
  77204. /**
  77205. * Execute a function that is physics-plugin specific.
  77206. * @param {Function} func the function that will be executed.
  77207. * It accepts two parameters: the physics world and the physics joint.
  77208. */
  77209. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  77210. func(this._physicsPlugin.world, this._physicsJoint);
  77211. };
  77212. //TODO check if the native joints are the same
  77213. //Joint Types
  77214. PhysicsJoint.DistanceJoint = 0;
  77215. PhysicsJoint.HingeJoint = 1;
  77216. PhysicsJoint.BallAndSocketJoint = 2;
  77217. PhysicsJoint.WheelJoint = 3;
  77218. PhysicsJoint.SliderJoint = 4;
  77219. //OIMO
  77220. PhysicsJoint.PrismaticJoint = 5;
  77221. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  77222. PhysicsJoint.UniversalJoint = 6;
  77223. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  77224. //Cannon
  77225. //Similar to a Ball-Joint. Different in params
  77226. PhysicsJoint.PointToPointJoint = 8;
  77227. //Cannon only at the moment
  77228. PhysicsJoint.SpringJoint = 9;
  77229. PhysicsJoint.LockJoint = 10;
  77230. return PhysicsJoint;
  77231. }());
  77232. BABYLON.PhysicsJoint = PhysicsJoint;
  77233. /**
  77234. * A class representing a physics distance joint.
  77235. */
  77236. var DistanceJoint = /** @class */ (function (_super) {
  77237. __extends(DistanceJoint, _super);
  77238. function DistanceJoint(jointData) {
  77239. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  77240. }
  77241. /**
  77242. * Update the predefined distance.
  77243. */
  77244. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  77245. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  77246. };
  77247. return DistanceJoint;
  77248. }(PhysicsJoint));
  77249. BABYLON.DistanceJoint = DistanceJoint;
  77250. var MotorEnabledJoint = /** @class */ (function (_super) {
  77251. __extends(MotorEnabledJoint, _super);
  77252. function MotorEnabledJoint(type, jointData) {
  77253. return _super.call(this, type, jointData) || this;
  77254. }
  77255. /**
  77256. * Set the motor values.
  77257. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77258. * @param {number} force the force to apply
  77259. * @param {number} maxForce max force for this motor.
  77260. */
  77261. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  77262. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77263. };
  77264. /**
  77265. * Set the motor's limits.
  77266. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77267. */
  77268. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77269. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77270. };
  77271. return MotorEnabledJoint;
  77272. }(PhysicsJoint));
  77273. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  77274. /**
  77275. * This class represents a single hinge physics joint
  77276. */
  77277. var HingeJoint = /** @class */ (function (_super) {
  77278. __extends(HingeJoint, _super);
  77279. function HingeJoint(jointData) {
  77280. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  77281. }
  77282. /**
  77283. * Set the motor values.
  77284. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77285. * @param {number} force the force to apply
  77286. * @param {number} maxForce max force for this motor.
  77287. */
  77288. HingeJoint.prototype.setMotor = function (force, maxForce) {
  77289. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77290. };
  77291. /**
  77292. * Set the motor's limits.
  77293. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77294. */
  77295. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77296. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77297. };
  77298. return HingeJoint;
  77299. }(MotorEnabledJoint));
  77300. BABYLON.HingeJoint = HingeJoint;
  77301. /**
  77302. * This class represents a dual hinge physics joint (same as wheel joint)
  77303. */
  77304. var Hinge2Joint = /** @class */ (function (_super) {
  77305. __extends(Hinge2Joint, _super);
  77306. function Hinge2Joint(jointData) {
  77307. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77308. }
  77309. /**
  77310. * Set the motor values.
  77311. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77312. * @param {number} force the force to apply
  77313. * @param {number} maxForce max force for this motor.
  77314. * @param {motorIndex} the motor's index, 0 or 1.
  77315. */
  77316. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77317. if (motorIndex === void 0) { motorIndex = 0; }
  77318. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77319. };
  77320. /**
  77321. * Set the motor limits.
  77322. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77323. * @param {number} upperLimit the upper limit
  77324. * @param {number} lowerLimit lower limit
  77325. * @param {motorIndex} the motor's index, 0 or 1.
  77326. */
  77327. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77328. if (motorIndex === void 0) { motorIndex = 0; }
  77329. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77330. };
  77331. return Hinge2Joint;
  77332. }(MotorEnabledJoint));
  77333. BABYLON.Hinge2Joint = Hinge2Joint;
  77334. })(BABYLON || (BABYLON = {}));
  77335. //# sourceMappingURL=babylon.physicsJoint.js.map
  77336. "use strict";
  77337. var BABYLON;
  77338. (function (BABYLON) {
  77339. var PhysicsImpostor = /** @class */ (function () {
  77340. function PhysicsImpostor(object, type, _options, _scene) {
  77341. if (_options === void 0) { _options = { mass: 0 }; }
  77342. var _this = this;
  77343. this.object = object;
  77344. this.type = type;
  77345. this._options = _options;
  77346. this._scene = _scene;
  77347. this._bodyUpdateRequired = false;
  77348. this._onBeforePhysicsStepCallbacks = new Array();
  77349. this._onAfterPhysicsStepCallbacks = new Array();
  77350. this._onPhysicsCollideCallbacks = [];
  77351. this._deltaPosition = BABYLON.Vector3.Zero();
  77352. this._isDisposed = false;
  77353. //temp variables for parent rotation calculations
  77354. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77355. this._tmpQuat = new BABYLON.Quaternion();
  77356. this._tmpQuat2 = new BABYLON.Quaternion();
  77357. /**
  77358. * this function is executed by the physics engine.
  77359. */
  77360. this.beforeStep = function () {
  77361. if (!_this._physicsEngine) {
  77362. return;
  77363. }
  77364. _this.object.translate(_this._deltaPosition, -1);
  77365. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77366. _this.object.computeWorldMatrix(false);
  77367. if (_this.object.parent && _this.object.rotationQuaternion) {
  77368. _this.getParentsRotation();
  77369. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77370. }
  77371. else {
  77372. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77373. }
  77374. if (!_this._options.disableBidirectionalTransformation) {
  77375. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77376. }
  77377. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77378. func(_this);
  77379. });
  77380. };
  77381. /**
  77382. * this function is executed by the physics engine.
  77383. */
  77384. this.afterStep = function () {
  77385. if (!_this._physicsEngine) {
  77386. return;
  77387. }
  77388. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77389. func(_this);
  77390. });
  77391. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77392. // object has now its world rotation. needs to be converted to local.
  77393. if (_this.object.parent && _this.object.rotationQuaternion) {
  77394. _this.getParentsRotation();
  77395. _this._tmpQuat.conjugateInPlace();
  77396. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77397. }
  77398. // take the position set and make it the absolute position of this object.
  77399. _this.object.setAbsolutePosition(_this.object.position);
  77400. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77401. _this.object.translate(_this._deltaPosition, 1);
  77402. };
  77403. /**
  77404. * Legacy collision detection event support
  77405. */
  77406. this.onCollideEvent = null;
  77407. //event and body object due to cannon's event-based architecture.
  77408. this.onCollide = function (e) {
  77409. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77410. return;
  77411. }
  77412. if (!_this._physicsEngine) {
  77413. return;
  77414. }
  77415. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77416. if (otherImpostor) {
  77417. // Legacy collision detection event support
  77418. if (_this.onCollideEvent) {
  77419. _this.onCollideEvent(_this, otherImpostor);
  77420. }
  77421. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77422. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77423. }).forEach(function (obj) {
  77424. obj.callback(_this, otherImpostor);
  77425. });
  77426. }
  77427. };
  77428. //sanity check!
  77429. if (!this.object) {
  77430. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77431. return;
  77432. }
  77433. //legacy support for old syntax.
  77434. if (!this._scene && object.getScene) {
  77435. this._scene = object.getScene();
  77436. }
  77437. if (!this._scene) {
  77438. return;
  77439. }
  77440. this._physicsEngine = this._scene.getPhysicsEngine();
  77441. if (!this._physicsEngine) {
  77442. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77443. }
  77444. else {
  77445. //set the object's quaternion, if not set
  77446. if (!this.object.rotationQuaternion) {
  77447. if (this.object.rotation) {
  77448. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77449. }
  77450. else {
  77451. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77452. }
  77453. }
  77454. //default options params
  77455. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77456. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77457. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77458. this._joints = [];
  77459. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77460. if (!this.object.parent || this._options.ignoreParent) {
  77461. this._init();
  77462. }
  77463. else if (this.object.parent.physicsImpostor) {
  77464. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77465. }
  77466. }
  77467. }
  77468. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77469. get: function () {
  77470. return this._isDisposed;
  77471. },
  77472. enumerable: true,
  77473. configurable: true
  77474. });
  77475. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77476. get: function () {
  77477. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77478. },
  77479. set: function (value) {
  77480. this.setMass(value);
  77481. },
  77482. enumerable: true,
  77483. configurable: true
  77484. });
  77485. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77486. get: function () {
  77487. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77488. },
  77489. set: function (value) {
  77490. if (!this._physicsEngine) {
  77491. return;
  77492. }
  77493. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77494. },
  77495. enumerable: true,
  77496. configurable: true
  77497. });
  77498. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77499. get: function () {
  77500. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77501. },
  77502. set: function (value) {
  77503. if (!this._physicsEngine) {
  77504. return;
  77505. }
  77506. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77507. },
  77508. enumerable: true,
  77509. configurable: true
  77510. });
  77511. /**
  77512. * This function will completly initialize this impostor.
  77513. * It will create a new body - but only if this mesh has no parent.
  77514. * If it has, this impostor will not be used other than to define the impostor
  77515. * of the child mesh.
  77516. */
  77517. PhysicsImpostor.prototype._init = function () {
  77518. if (!this._physicsEngine) {
  77519. return;
  77520. }
  77521. this._physicsEngine.removeImpostor(this);
  77522. this.physicsBody = null;
  77523. this._parent = this._parent || this._getPhysicsParent();
  77524. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77525. this._physicsEngine.addImpostor(this);
  77526. }
  77527. };
  77528. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77529. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77530. var parentMesh = this.object.parent;
  77531. return parentMesh.physicsImpostor;
  77532. }
  77533. return null;
  77534. };
  77535. /**
  77536. * Should a new body be generated.
  77537. */
  77538. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77539. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77540. };
  77541. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77542. this.forceUpdate();
  77543. };
  77544. /**
  77545. * Force a regeneration of this or the parent's impostor's body.
  77546. * Use under cautious - This will remove all joints already implemented.
  77547. */
  77548. PhysicsImpostor.prototype.forceUpdate = function () {
  77549. this._init();
  77550. if (this.parent && !this._options.ignoreParent) {
  77551. this.parent.forceUpdate();
  77552. }
  77553. };
  77554. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77555. /*public get mesh(): AbstractMesh {
  77556. return this._mesh;
  77557. }*/
  77558. /**
  77559. * Gets the body that holds this impostor. Either its own, or its parent.
  77560. */
  77561. get: function () {
  77562. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77563. },
  77564. /**
  77565. * Set the physics body. Used mainly by the physics engine/plugin
  77566. */
  77567. set: function (physicsBody) {
  77568. if (this._physicsBody && this._physicsEngine) {
  77569. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77570. }
  77571. this._physicsBody = physicsBody;
  77572. this.resetUpdateFlags();
  77573. },
  77574. enumerable: true,
  77575. configurable: true
  77576. });
  77577. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77578. get: function () {
  77579. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77580. },
  77581. set: function (value) {
  77582. this._parent = value;
  77583. },
  77584. enumerable: true,
  77585. configurable: true
  77586. });
  77587. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77588. this._bodyUpdateRequired = false;
  77589. };
  77590. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77591. if (this.object.getBoundingInfo) {
  77592. var q = this.object.rotationQuaternion;
  77593. //reset rotation
  77594. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77595. //calculate the world matrix with no rotation
  77596. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77597. var boundingInfo = this.object.getBoundingInfo();
  77598. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77599. //bring back the rotation
  77600. this.object.rotationQuaternion = q;
  77601. //calculate the world matrix with the new rotation
  77602. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77603. return size;
  77604. }
  77605. else {
  77606. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77607. }
  77608. };
  77609. PhysicsImpostor.prototype.getObjectCenter = function () {
  77610. if (this.object.getBoundingInfo) {
  77611. var boundingInfo = this.object.getBoundingInfo();
  77612. return boundingInfo.boundingBox.centerWorld;
  77613. }
  77614. else {
  77615. return this.object.position;
  77616. }
  77617. };
  77618. /**
  77619. * Get a specific parametes from the options parameter.
  77620. */
  77621. PhysicsImpostor.prototype.getParam = function (paramName) {
  77622. return this._options[paramName];
  77623. };
  77624. /**
  77625. * Sets a specific parameter in the options given to the physics plugin
  77626. */
  77627. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77628. this._options[paramName] = value;
  77629. this._bodyUpdateRequired = true;
  77630. };
  77631. /**
  77632. * Specifically change the body's mass option. Won't recreate the physics body object
  77633. */
  77634. PhysicsImpostor.prototype.setMass = function (mass) {
  77635. if (this.getParam("mass") !== mass) {
  77636. this.setParam("mass", mass);
  77637. }
  77638. if (this._physicsEngine) {
  77639. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77640. }
  77641. };
  77642. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77643. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77644. };
  77645. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77646. if (this._physicsEngine) {
  77647. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77648. }
  77649. };
  77650. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77651. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77652. };
  77653. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77654. if (this._physicsEngine) {
  77655. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77656. }
  77657. };
  77658. /**
  77659. * Execute a function with the physics plugin native code.
  77660. * Provide a function the will have two variables - the world object and the physics body object.
  77661. */
  77662. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77663. if (this._physicsEngine) {
  77664. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77665. }
  77666. };
  77667. /**
  77668. * Register a function that will be executed before the physics world is stepping forward.
  77669. */
  77670. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77671. this._onBeforePhysicsStepCallbacks.push(func);
  77672. };
  77673. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77674. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77675. if (index > -1) {
  77676. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77677. }
  77678. else {
  77679. BABYLON.Tools.Warn("Function to remove was not found");
  77680. }
  77681. };
  77682. /**
  77683. * Register a function that will be executed after the physics step
  77684. */
  77685. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77686. this._onAfterPhysicsStepCallbacks.push(func);
  77687. };
  77688. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77689. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77690. if (index > -1) {
  77691. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77692. }
  77693. else {
  77694. BABYLON.Tools.Warn("Function to remove was not found");
  77695. }
  77696. };
  77697. /**
  77698. * register a function that will be executed when this impostor collides against a different body.
  77699. */
  77700. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77701. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77702. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77703. };
  77704. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77705. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77706. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77707. if (index > -1) {
  77708. this._onPhysicsCollideCallbacks.splice(index, 1);
  77709. }
  77710. else {
  77711. BABYLON.Tools.Warn("Function to remove was not found");
  77712. }
  77713. };
  77714. PhysicsImpostor.prototype.getParentsRotation = function () {
  77715. var parent = this.object.parent;
  77716. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77717. while (parent) {
  77718. if (parent.rotationQuaternion) {
  77719. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77720. }
  77721. else {
  77722. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77723. }
  77724. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77725. parent = parent.parent;
  77726. }
  77727. return this._tmpQuat;
  77728. };
  77729. /**
  77730. * Apply a force
  77731. */
  77732. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77733. if (this._physicsEngine) {
  77734. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77735. }
  77736. return this;
  77737. };
  77738. /**
  77739. * Apply an impulse
  77740. */
  77741. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77742. if (this._physicsEngine) {
  77743. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77744. }
  77745. return this;
  77746. };
  77747. /**
  77748. * A help function to create a joint.
  77749. */
  77750. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77751. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77752. this.addJoint(otherImpostor, joint);
  77753. return this;
  77754. };
  77755. /**
  77756. * Add a joint to this impostor with a different impostor.
  77757. */
  77758. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77759. this._joints.push({
  77760. otherImpostor: otherImpostor,
  77761. joint: joint
  77762. });
  77763. if (this._physicsEngine) {
  77764. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77765. }
  77766. return this;
  77767. };
  77768. /**
  77769. * Will keep this body still, in a sleep mode.
  77770. */
  77771. PhysicsImpostor.prototype.sleep = function () {
  77772. if (this._physicsEngine) {
  77773. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77774. }
  77775. return this;
  77776. };
  77777. /**
  77778. * Wake the body up.
  77779. */
  77780. PhysicsImpostor.prototype.wakeUp = function () {
  77781. if (this._physicsEngine) {
  77782. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77783. }
  77784. return this;
  77785. };
  77786. PhysicsImpostor.prototype.clone = function (newObject) {
  77787. if (!newObject)
  77788. return null;
  77789. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77790. };
  77791. PhysicsImpostor.prototype.dispose = function () {
  77792. var _this = this;
  77793. //no dispose if no physics engine is available.
  77794. if (!this._physicsEngine) {
  77795. return;
  77796. }
  77797. this._joints.forEach(function (j) {
  77798. if (_this._physicsEngine) {
  77799. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77800. }
  77801. });
  77802. //dispose the physics body
  77803. this._physicsEngine.removeImpostor(this);
  77804. if (this.parent) {
  77805. this.parent.forceUpdate();
  77806. }
  77807. else {
  77808. /*this._object.getChildMeshes().forEach(function(mesh) {
  77809. if (mesh.physicsImpostor) {
  77810. if (disposeChildren) {
  77811. mesh.physicsImpostor.dispose();
  77812. mesh.physicsImpostor = null;
  77813. }
  77814. }
  77815. })*/
  77816. }
  77817. this._isDisposed = true;
  77818. };
  77819. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77820. this._deltaPosition.copyFrom(position);
  77821. };
  77822. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77823. if (!this._deltaRotation) {
  77824. this._deltaRotation = new BABYLON.Quaternion();
  77825. }
  77826. this._deltaRotation.copyFrom(rotation);
  77827. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77828. };
  77829. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77830. if (this._physicsEngine) {
  77831. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77832. }
  77833. return this;
  77834. };
  77835. PhysicsImpostor.prototype.getRadius = function () {
  77836. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77837. };
  77838. /**
  77839. * Sync a bone with this impostor
  77840. * @param bone The bone to sync to the impostor.
  77841. * @param boneMesh The mesh that the bone is influencing.
  77842. * @param jointPivot The pivot of the joint / bone in local space.
  77843. * @param distToJoint Optional distance from the impostor to the joint.
  77844. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77845. */
  77846. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77847. var tempVec = PhysicsImpostor._tmpVecs[0];
  77848. var mesh = this.object;
  77849. if (mesh.rotationQuaternion) {
  77850. if (adjustRotation) {
  77851. var tempQuat = PhysicsImpostor._tmpQuat;
  77852. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77853. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77854. }
  77855. else {
  77856. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77857. }
  77858. }
  77859. tempVec.x = 0;
  77860. tempVec.y = 0;
  77861. tempVec.z = 0;
  77862. if (jointPivot) {
  77863. tempVec.x = jointPivot.x;
  77864. tempVec.y = jointPivot.y;
  77865. tempVec.z = jointPivot.z;
  77866. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77867. if (distToJoint === undefined || distToJoint === null) {
  77868. distToJoint = jointPivot.length();
  77869. }
  77870. tempVec.x *= distToJoint;
  77871. tempVec.y *= distToJoint;
  77872. tempVec.z *= distToJoint;
  77873. }
  77874. if (bone.getParent()) {
  77875. tempVec.addInPlace(mesh.getAbsolutePosition());
  77876. bone.setAbsolutePosition(tempVec, boneMesh);
  77877. }
  77878. else {
  77879. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77880. boneMesh.position.x -= tempVec.x;
  77881. boneMesh.position.y -= tempVec.y;
  77882. boneMesh.position.z -= tempVec.z;
  77883. }
  77884. };
  77885. /**
  77886. * Sync impostor to a bone
  77887. * @param bone The bone that the impostor will be synced to.
  77888. * @param boneMesh The mesh that the bone is influencing.
  77889. * @param jointPivot The pivot of the joint / bone in local space.
  77890. * @param distToJoint Optional distance from the impostor to the joint.
  77891. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77892. * @param boneAxis Optional vector3 axis the bone is aligned with
  77893. */
  77894. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77895. var mesh = this.object;
  77896. if (mesh.rotationQuaternion) {
  77897. if (adjustRotation) {
  77898. var tempQuat = PhysicsImpostor._tmpQuat;
  77899. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77900. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77901. }
  77902. else {
  77903. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77904. }
  77905. }
  77906. var pos = PhysicsImpostor._tmpVecs[0];
  77907. var boneDir = PhysicsImpostor._tmpVecs[1];
  77908. if (!boneAxis) {
  77909. boneAxis = PhysicsImpostor._tmpVecs[2];
  77910. boneAxis.x = 0;
  77911. boneAxis.y = 1;
  77912. boneAxis.z = 0;
  77913. }
  77914. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77915. bone.getAbsolutePositionToRef(boneMesh, pos);
  77916. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77917. distToJoint = jointPivot.length();
  77918. }
  77919. if (distToJoint !== undefined && distToJoint !== null) {
  77920. pos.x += boneDir.x * distToJoint;
  77921. pos.y += boneDir.y * distToJoint;
  77922. pos.z += boneDir.z * distToJoint;
  77923. }
  77924. mesh.setAbsolutePosition(pos);
  77925. };
  77926. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77927. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77928. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77929. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77930. //Impostor types
  77931. PhysicsImpostor.NoImpostor = 0;
  77932. PhysicsImpostor.SphereImpostor = 1;
  77933. PhysicsImpostor.BoxImpostor = 2;
  77934. PhysicsImpostor.PlaneImpostor = 3;
  77935. PhysicsImpostor.MeshImpostor = 4;
  77936. PhysicsImpostor.CylinderImpostor = 7;
  77937. PhysicsImpostor.ParticleImpostor = 8;
  77938. PhysicsImpostor.HeightmapImpostor = 9;
  77939. return PhysicsImpostor;
  77940. }());
  77941. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77942. })(BABYLON || (BABYLON = {}));
  77943. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77944. "use strict";
  77945. var BABYLON;
  77946. (function (BABYLON) {
  77947. var PhysicsEngine = /** @class */ (function () {
  77948. function PhysicsEngine(gravity, _physicsPlugin) {
  77949. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77950. this._physicsPlugin = _physicsPlugin;
  77951. //new methods and parameters
  77952. this._impostors = [];
  77953. this._joints = [];
  77954. if (!this._physicsPlugin.isSupported()) {
  77955. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77956. + "Please make sure it is included.");
  77957. }
  77958. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77959. this.setGravity(gravity);
  77960. this.setTimeStep();
  77961. }
  77962. PhysicsEngine.prototype.setGravity = function (gravity) {
  77963. this.gravity = gravity;
  77964. this._physicsPlugin.setGravity(this.gravity);
  77965. };
  77966. /**
  77967. * Set the time step of the physics engine.
  77968. * default is 1/60.
  77969. * To slow it down, enter 1/600 for example.
  77970. * To speed it up, 1/30
  77971. * @param {number} newTimeStep the new timestep to apply to this world.
  77972. */
  77973. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77974. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77975. this._physicsPlugin.setTimeStep(newTimeStep);
  77976. };
  77977. /**
  77978. * Get the time step of the physics engine.
  77979. */
  77980. PhysicsEngine.prototype.getTimeStep = function () {
  77981. return this._physicsPlugin.getTimeStep();
  77982. };
  77983. PhysicsEngine.prototype.dispose = function () {
  77984. this._impostors.forEach(function (impostor) {
  77985. impostor.dispose();
  77986. });
  77987. this._physicsPlugin.dispose();
  77988. };
  77989. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77990. return this._physicsPlugin.name;
  77991. };
  77992. /**
  77993. * Adding a new impostor for the impostor tracking.
  77994. * This will be done by the impostor itself.
  77995. * @param {PhysicsImpostor} impostor the impostor to add
  77996. */
  77997. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77998. impostor.uniqueId = this._impostors.push(impostor);
  77999. //if no parent, generate the body
  78000. if (!impostor.parent) {
  78001. this._physicsPlugin.generatePhysicsBody(impostor);
  78002. }
  78003. };
  78004. /**
  78005. * Remove an impostor from the engine.
  78006. * This impostor and its mesh will not longer be updated by the physics engine.
  78007. * @param {PhysicsImpostor} impostor the impostor to remove
  78008. */
  78009. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  78010. var index = this._impostors.indexOf(impostor);
  78011. if (index > -1) {
  78012. var removed = this._impostors.splice(index, 1);
  78013. //Is it needed?
  78014. if (removed.length) {
  78015. //this will also remove it from the world.
  78016. removed[0].physicsBody = null;
  78017. }
  78018. }
  78019. };
  78020. /**
  78021. * Add a joint to the physics engine
  78022. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  78023. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  78024. * @param {PhysicsJoint} the joint that will connect both impostors.
  78025. */
  78026. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  78027. var impostorJoint = {
  78028. mainImpostor: mainImpostor,
  78029. connectedImpostor: connectedImpostor,
  78030. joint: joint
  78031. };
  78032. joint.physicsPlugin = this._physicsPlugin;
  78033. this._joints.push(impostorJoint);
  78034. this._physicsPlugin.generateJoint(impostorJoint);
  78035. };
  78036. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  78037. var matchingJoints = this._joints.filter(function (impostorJoint) {
  78038. return (impostorJoint.connectedImpostor === connectedImpostor
  78039. && impostorJoint.joint === joint
  78040. && impostorJoint.mainImpostor === mainImpostor);
  78041. });
  78042. if (matchingJoints.length) {
  78043. this._physicsPlugin.removeJoint(matchingJoints[0]);
  78044. //TODO remove it from the list as well
  78045. }
  78046. };
  78047. /**
  78048. * Called by the scene. no need to call it.
  78049. */
  78050. PhysicsEngine.prototype._step = function (delta) {
  78051. var _this = this;
  78052. //check if any mesh has no body / requires an update
  78053. this._impostors.forEach(function (impostor) {
  78054. if (impostor.isBodyInitRequired()) {
  78055. _this._physicsPlugin.generatePhysicsBody(impostor);
  78056. }
  78057. });
  78058. if (delta > 0.1) {
  78059. delta = 0.1;
  78060. }
  78061. else if (delta <= 0) {
  78062. delta = 1.0 / 60.0;
  78063. }
  78064. this._physicsPlugin.executeStep(delta, this._impostors);
  78065. };
  78066. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  78067. return this._physicsPlugin;
  78068. };
  78069. PhysicsEngine.prototype.getImpostors = function () {
  78070. return this._impostors;
  78071. };
  78072. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  78073. for (var i = 0; i < this._impostors.length; ++i) {
  78074. if (this._impostors[i].object === object) {
  78075. return this._impostors[i];
  78076. }
  78077. }
  78078. return null;
  78079. };
  78080. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  78081. for (var i = 0; i < this._impostors.length; ++i) {
  78082. if (this._impostors[i].physicsBody === body) {
  78083. return this._impostors[i];
  78084. }
  78085. }
  78086. return null;
  78087. };
  78088. // Statics
  78089. PhysicsEngine.Epsilon = 0.001;
  78090. return PhysicsEngine;
  78091. }());
  78092. BABYLON.PhysicsEngine = PhysicsEngine;
  78093. })(BABYLON || (BABYLON = {}));
  78094. //# sourceMappingURL=babylon.physicsEngine.js.map
  78095. "use strict";
  78096. var BABYLON;
  78097. (function (BABYLON) {
  78098. var PhysicsHelper = /** @class */ (function () {
  78099. function PhysicsHelper(scene) {
  78100. this._scene = scene;
  78101. this._physicsEngine = this._scene.getPhysicsEngine();
  78102. if (!this._physicsEngine) {
  78103. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  78104. }
  78105. }
  78106. /**
  78107. * @param {Vector3} origin the origin of the explosion
  78108. * @param {number} radius the explosion radius
  78109. * @param {number} strength the explosion strength
  78110. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78111. */
  78112. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  78113. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78114. if (!this._physicsEngine) {
  78115. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  78116. return null;
  78117. }
  78118. var impostors = this._physicsEngine.getImpostors();
  78119. if (impostors.length === 0) {
  78120. return null;
  78121. }
  78122. var event = new PhysicsRadialExplosionEvent(this._scene);
  78123. impostors.forEach(function (impostor) {
  78124. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78125. if (!impostorForceAndContactPoint) {
  78126. return;
  78127. }
  78128. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78129. });
  78130. event.dispose(false);
  78131. return event;
  78132. };
  78133. /**
  78134. * @param {Vector3} origin the origin of the explosion
  78135. * @param {number} radius the explosion radius
  78136. * @param {number} strength the explosion strength
  78137. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78138. */
  78139. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  78140. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78141. if (!this._physicsEngine) {
  78142. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78143. return null;
  78144. }
  78145. var impostors = this._physicsEngine.getImpostors();
  78146. if (impostors.length === 0) {
  78147. return null;
  78148. }
  78149. var event = new PhysicsRadialExplosionEvent(this._scene);
  78150. impostors.forEach(function (impostor) {
  78151. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78152. if (!impostorForceAndContactPoint) {
  78153. return;
  78154. }
  78155. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78156. });
  78157. event.dispose(false);
  78158. return event;
  78159. };
  78160. /**
  78161. * @param {Vector3} origin the origin of the explosion
  78162. * @param {number} radius the explosion radius
  78163. * @param {number} strength the explosion strength
  78164. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78165. */
  78166. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  78167. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78168. if (!this._physicsEngine) {
  78169. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78170. return null;
  78171. }
  78172. var impostors = this._physicsEngine.getImpostors();
  78173. if (impostors.length === 0) {
  78174. return null;
  78175. }
  78176. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  78177. event.dispose(false);
  78178. return event;
  78179. };
  78180. /**
  78181. * @param {Vector3} origin the origin of the updraft
  78182. * @param {number} radius the radius of the updraft
  78183. * @param {number} strength the strength of the updraft
  78184. * @param {number} height the height of the updraft
  78185. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  78186. */
  78187. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  78188. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  78189. if (!this._physicsEngine) {
  78190. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78191. return null;
  78192. }
  78193. if (this._physicsEngine.getImpostors().length === 0) {
  78194. return null;
  78195. }
  78196. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  78197. event.dispose(false);
  78198. return event;
  78199. };
  78200. /**
  78201. * @param {Vector3} origin the of the vortex
  78202. * @param {number} radius the radius of the vortex
  78203. * @param {number} strength the strength of the vortex
  78204. * @param {number} height the height of the vortex
  78205. */
  78206. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  78207. if (!this._physicsEngine) {
  78208. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78209. return null;
  78210. }
  78211. if (this._physicsEngine.getImpostors().length === 0) {
  78212. return null;
  78213. }
  78214. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  78215. event.dispose(false);
  78216. return event;
  78217. };
  78218. return PhysicsHelper;
  78219. }());
  78220. BABYLON.PhysicsHelper = PhysicsHelper;
  78221. /***** Radial explosion *****/
  78222. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  78223. function PhysicsRadialExplosionEvent(scene) {
  78224. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  78225. this._rays = [];
  78226. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  78227. this._scene = scene;
  78228. }
  78229. /**
  78230. * Returns the data related to the radial explosion event (sphere & rays).
  78231. * @returns {PhysicsRadialExplosionEventData}
  78232. */
  78233. PhysicsRadialExplosionEvent.prototype.getData = function () {
  78234. this._dataFetched = true;
  78235. return {
  78236. sphere: this._sphere,
  78237. rays: this._rays,
  78238. };
  78239. };
  78240. /**
  78241. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  78242. * @param impostor
  78243. * @param {Vector3} origin the origin of the explosion
  78244. * @param {number} radius the explosion radius
  78245. * @param {number} strength the explosion strength
  78246. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  78247. * @returns {Nullable<PhysicsForceAndContactPoint>}
  78248. */
  78249. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  78250. if (impostor.mass === 0) {
  78251. return null;
  78252. }
  78253. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  78254. return null;
  78255. }
  78256. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78257. return null;
  78258. }
  78259. var impostorObjectCenter = impostor.getObjectCenter();
  78260. var direction = impostorObjectCenter.subtract(origin);
  78261. var ray = new BABYLON.Ray(origin, direction, radius);
  78262. this._rays.push(ray);
  78263. var hit = ray.intersectsMesh(impostor.object);
  78264. var contactPoint = hit.pickedPoint;
  78265. if (!contactPoint) {
  78266. return null;
  78267. }
  78268. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  78269. if (distanceFromOrigin > radius) {
  78270. return null;
  78271. }
  78272. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  78273. ? strength
  78274. : strength * (1 - (distanceFromOrigin / radius));
  78275. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78276. return { force: force, contactPoint: contactPoint };
  78277. };
  78278. /**
  78279. * Disposes the sphere.
  78280. * @param {bolean} force
  78281. */
  78282. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  78283. var _this = this;
  78284. if (force === void 0) { force = true; }
  78285. if (force) {
  78286. this._sphere.dispose();
  78287. }
  78288. else {
  78289. setTimeout(function () {
  78290. if (!_this._dataFetched) {
  78291. _this._sphere.dispose();
  78292. }
  78293. }, 0);
  78294. }
  78295. };
  78296. /*** Helpers ***/
  78297. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  78298. if (!this._sphere) {
  78299. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  78300. this._sphere.isVisible = false;
  78301. }
  78302. };
  78303. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  78304. var impostorObject = impostor.object;
  78305. this._prepareSphere();
  78306. this._sphere.position = origin;
  78307. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78308. this._sphere._updateBoundingInfo();
  78309. this._sphere.computeWorldMatrix(true);
  78310. return this._sphere.intersectsMesh(impostorObject, true);
  78311. };
  78312. return PhysicsRadialExplosionEvent;
  78313. }());
  78314. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78315. /***** Gravitational Field *****/
  78316. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78317. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78318. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78319. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78320. this._physicsHelper = physicsHelper;
  78321. this._scene = scene;
  78322. this._origin = origin;
  78323. this._radius = radius;
  78324. this._strength = strength;
  78325. this._falloff = falloff;
  78326. this._tickCallback = this._tick.bind(this);
  78327. }
  78328. /**
  78329. * Returns the data related to the gravitational field event (sphere).
  78330. * @returns {PhysicsGravitationalFieldEventData}
  78331. */
  78332. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78333. this._dataFetched = true;
  78334. return {
  78335. sphere: this._sphere,
  78336. };
  78337. };
  78338. /**
  78339. * Enables the gravitational field.
  78340. */
  78341. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78342. this._tickCallback.call(this);
  78343. this._scene.registerBeforeRender(this._tickCallback);
  78344. };
  78345. /**
  78346. * Disables the gravitational field.
  78347. */
  78348. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78349. this._scene.unregisterBeforeRender(this._tickCallback);
  78350. };
  78351. /**
  78352. * Disposes the sphere.
  78353. * @param {bolean} force
  78354. */
  78355. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78356. var _this = this;
  78357. if (force === void 0) { force = true; }
  78358. if (force) {
  78359. this._sphere.dispose();
  78360. }
  78361. else {
  78362. setTimeout(function () {
  78363. if (!_this._dataFetched) {
  78364. _this._sphere.dispose();
  78365. }
  78366. }, 0);
  78367. }
  78368. };
  78369. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78370. // Since the params won't change, we fetch the event only once
  78371. if (this._sphere) {
  78372. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78373. }
  78374. else {
  78375. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78376. if (radialExplosionEvent) {
  78377. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78378. }
  78379. }
  78380. };
  78381. return PhysicsGravitationalFieldEvent;
  78382. }());
  78383. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78384. /***** Updraft *****/
  78385. var PhysicsUpdraftEvent = /** @class */ (function () {
  78386. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78387. this._scene = _scene;
  78388. this._origin = _origin;
  78389. this._radius = _radius;
  78390. this._strength = _strength;
  78391. this._height = _height;
  78392. this._updraftMode = _updraftMode;
  78393. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78394. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78395. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78396. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78397. this._physicsEngine = this._scene.getPhysicsEngine();
  78398. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78399. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78400. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78401. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78402. }
  78403. this._tickCallback = this._tick.bind(this);
  78404. }
  78405. /**
  78406. * Returns the data related to the updraft event (cylinder).
  78407. * @returns {PhysicsUpdraftEventData}
  78408. */
  78409. PhysicsUpdraftEvent.prototype.getData = function () {
  78410. this._dataFetched = true;
  78411. return {
  78412. cylinder: this._cylinder,
  78413. };
  78414. };
  78415. /**
  78416. * Enables the updraft.
  78417. */
  78418. PhysicsUpdraftEvent.prototype.enable = function () {
  78419. this._tickCallback.call(this);
  78420. this._scene.registerBeforeRender(this._tickCallback);
  78421. };
  78422. /**
  78423. * Disables the cortex.
  78424. */
  78425. PhysicsUpdraftEvent.prototype.disable = function () {
  78426. this._scene.unregisterBeforeRender(this._tickCallback);
  78427. };
  78428. /**
  78429. * Disposes the sphere.
  78430. * @param {bolean} force
  78431. */
  78432. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78433. var _this = this;
  78434. if (force === void 0) { force = true; }
  78435. if (force) {
  78436. this._cylinder.dispose();
  78437. }
  78438. else {
  78439. setTimeout(function () {
  78440. if (!_this._dataFetched) {
  78441. _this._cylinder.dispose();
  78442. }
  78443. }, 0);
  78444. }
  78445. };
  78446. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78447. if (impostor.mass === 0) {
  78448. return null;
  78449. }
  78450. if (!this._intersectsWithCylinder(impostor)) {
  78451. return null;
  78452. }
  78453. var impostorObjectCenter = impostor.getObjectCenter();
  78454. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78455. var direction = this._originDirection;
  78456. }
  78457. else {
  78458. var direction = impostorObjectCenter.subtract(this._originTop);
  78459. }
  78460. var multiplier = this._strength * -1;
  78461. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78462. return { force: force, contactPoint: impostorObjectCenter };
  78463. };
  78464. PhysicsUpdraftEvent.prototype._tick = function () {
  78465. var _this = this;
  78466. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78467. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78468. if (!impostorForceAndContactPoint) {
  78469. return;
  78470. }
  78471. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78472. });
  78473. };
  78474. /*** Helpers ***/
  78475. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78476. if (!this._cylinder) {
  78477. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78478. height: this._height,
  78479. diameter: this._radius * 2,
  78480. }, this._scene);
  78481. this._cylinder.isVisible = false;
  78482. }
  78483. };
  78484. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78485. var impostorObject = impostor.object;
  78486. this._prepareCylinder();
  78487. this._cylinder.position = this._cylinderPosition;
  78488. return this._cylinder.intersectsMesh(impostorObject, true);
  78489. };
  78490. return PhysicsUpdraftEvent;
  78491. }());
  78492. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78493. /***** Vortex *****/
  78494. var PhysicsVortexEvent = /** @class */ (function () {
  78495. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78496. this._scene = _scene;
  78497. this._origin = _origin;
  78498. this._radius = _radius;
  78499. this._strength = _strength;
  78500. this._height = _height;
  78501. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78502. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78503. this._updraftMultiplier = 0.02;
  78504. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78505. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78506. this._physicsEngine = this._scene.getPhysicsEngine();
  78507. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78508. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78509. this._tickCallback = this._tick.bind(this);
  78510. }
  78511. /**
  78512. * Returns the data related to the vortex event (cylinder).
  78513. * @returns {PhysicsVortexEventData}
  78514. */
  78515. PhysicsVortexEvent.prototype.getData = function () {
  78516. this._dataFetched = true;
  78517. return {
  78518. cylinder: this._cylinder,
  78519. };
  78520. };
  78521. /**
  78522. * Enables the vortex.
  78523. */
  78524. PhysicsVortexEvent.prototype.enable = function () {
  78525. this._tickCallback.call(this);
  78526. this._scene.registerBeforeRender(this._tickCallback);
  78527. };
  78528. /**
  78529. * Disables the cortex.
  78530. */
  78531. PhysicsVortexEvent.prototype.disable = function () {
  78532. this._scene.unregisterBeforeRender(this._tickCallback);
  78533. };
  78534. /**
  78535. * Disposes the sphere.
  78536. * @param {bolean} force
  78537. */
  78538. PhysicsVortexEvent.prototype.dispose = function (force) {
  78539. var _this = this;
  78540. if (force === void 0) { force = true; }
  78541. if (force) {
  78542. this._cylinder.dispose();
  78543. }
  78544. else {
  78545. setTimeout(function () {
  78546. if (!_this._dataFetched) {
  78547. _this._cylinder.dispose();
  78548. }
  78549. }, 0);
  78550. }
  78551. };
  78552. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78553. if (impostor.mass === 0) {
  78554. return null;
  78555. }
  78556. if (!this._intersectsWithCylinder(impostor)) {
  78557. return null;
  78558. }
  78559. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78560. return null;
  78561. }
  78562. var impostorObjectCenter = impostor.getObjectCenter();
  78563. 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)
  78564. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78565. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78566. var hit = ray.intersectsMesh(impostor.object);
  78567. var contactPoint = hit.pickedPoint;
  78568. if (!contactPoint) {
  78569. return null;
  78570. }
  78571. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78572. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78573. var directionToOrigin = contactPoint.normalize();
  78574. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78575. directionToOrigin = directionToOrigin.negate();
  78576. }
  78577. // TODO: find a more physically based solution
  78578. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78579. var forceX = directionToOrigin.x * this._strength / 8;
  78580. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78581. var forceZ = directionToOrigin.z * this._strength / 8;
  78582. }
  78583. else {
  78584. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78585. var forceY = this._originTop.y * this._updraftMultiplier;
  78586. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78587. }
  78588. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78589. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78590. return { force: force, contactPoint: impostorObjectCenter };
  78591. };
  78592. PhysicsVortexEvent.prototype._tick = function () {
  78593. var _this = this;
  78594. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78595. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78596. if (!impostorForceAndContactPoint) {
  78597. return;
  78598. }
  78599. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78600. });
  78601. };
  78602. /*** Helpers ***/
  78603. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78604. if (!this._cylinder) {
  78605. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78606. height: this._height,
  78607. diameter: this._radius * 2,
  78608. }, this._scene);
  78609. this._cylinder.isVisible = false;
  78610. }
  78611. };
  78612. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78613. var impostorObject = impostor.object;
  78614. this._prepareCylinder();
  78615. this._cylinder.position = this._cylinderPosition;
  78616. return this._cylinder.intersectsMesh(impostorObject, true);
  78617. };
  78618. return PhysicsVortexEvent;
  78619. }());
  78620. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78621. /***** Enums *****/
  78622. /**
  78623. * The strenght of the force in correspondence to the distance of the affected object
  78624. */
  78625. var PhysicsRadialImpulseFalloff;
  78626. (function (PhysicsRadialImpulseFalloff) {
  78627. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78628. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78629. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78630. /**
  78631. * The strenght of the force in correspondence to the distance of the affected object
  78632. */
  78633. var PhysicsUpdraftMode;
  78634. (function (PhysicsUpdraftMode) {
  78635. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78636. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78637. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78638. })(BABYLON || (BABYLON = {}));
  78639. //# sourceMappingURL=babylon.physicsHelper.js.map
  78640. "use strict";
  78641. var BABYLON;
  78642. (function (BABYLON) {
  78643. var CannonJSPlugin = /** @class */ (function () {
  78644. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78645. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78646. if (iterations === void 0) { iterations = 10; }
  78647. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78648. this.name = "CannonJSPlugin";
  78649. this._physicsMaterials = new Array();
  78650. this._fixedTimeStep = 1 / 60;
  78651. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78652. this.BJSCANNON = CANNON;
  78653. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78654. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78655. this._tmpPosition = BABYLON.Vector3.Zero();
  78656. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78657. this._tmpUnityRotation = new BABYLON.Quaternion();
  78658. if (!this.isSupported()) {
  78659. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78660. return;
  78661. }
  78662. this._extendNamespace();
  78663. this.world = new this.BJSCANNON.World();
  78664. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78665. this.world.solver.iterations = iterations;
  78666. }
  78667. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78668. this.world.gravity.copy(gravity);
  78669. };
  78670. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78671. this._fixedTimeStep = timeStep;
  78672. };
  78673. CannonJSPlugin.prototype.getTimeStep = function () {
  78674. return this._fixedTimeStep;
  78675. };
  78676. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78677. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78678. };
  78679. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78680. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78681. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78682. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78683. };
  78684. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78685. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78686. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78687. impostor.physicsBody.applyForce(impulse, worldPoint);
  78688. };
  78689. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78690. //parent-child relationship. Does this impostor has a parent impostor?
  78691. if (impostor.parent) {
  78692. if (impostor.physicsBody) {
  78693. this.removePhysicsBody(impostor);
  78694. //TODO is that needed?
  78695. impostor.forceUpdate();
  78696. }
  78697. return;
  78698. }
  78699. //should a new body be created for this impostor?
  78700. if (impostor.isBodyInitRequired()) {
  78701. var shape = this._createShape(impostor);
  78702. //unregister events, if body is being changed
  78703. var oldBody = impostor.physicsBody;
  78704. if (oldBody) {
  78705. this.removePhysicsBody(impostor);
  78706. }
  78707. //create the body and material
  78708. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78709. var bodyCreationObject = {
  78710. mass: impostor.getParam("mass"),
  78711. material: material
  78712. };
  78713. // A simple extend, in case native options were used.
  78714. var nativeOptions = impostor.getParam("nativeOptions");
  78715. for (var key in nativeOptions) {
  78716. if (nativeOptions.hasOwnProperty(key)) {
  78717. bodyCreationObject[key] = nativeOptions[key];
  78718. }
  78719. }
  78720. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78721. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78722. this.world.addEventListener("preStep", impostor.beforeStep);
  78723. this.world.addEventListener("postStep", impostor.afterStep);
  78724. impostor.physicsBody.addShape(shape);
  78725. this.world.add(impostor.physicsBody);
  78726. //try to keep the body moving in the right direction by taking old properties.
  78727. //Should be tested!
  78728. if (oldBody) {
  78729. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78730. impostor.physicsBody[param].copy(oldBody[param]);
  78731. });
  78732. }
  78733. this._processChildMeshes(impostor);
  78734. }
  78735. //now update the body's transformation
  78736. this._updatePhysicsBodyTransformation(impostor);
  78737. };
  78738. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78739. var _this = this;
  78740. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78741. var currentRotation = mainImpostor.object.rotationQuaternion;
  78742. if (meshChildren.length) {
  78743. var processMesh = function (localPosition, mesh) {
  78744. if (!currentRotation || !mesh.rotationQuaternion) {
  78745. return;
  78746. }
  78747. var childImpostor = mesh.getPhysicsImpostor();
  78748. if (childImpostor) {
  78749. var parent = childImpostor.parent;
  78750. if (parent !== mainImpostor) {
  78751. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78752. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78753. if (childImpostor.physicsBody) {
  78754. _this.removePhysicsBody(childImpostor);
  78755. childImpostor.physicsBody = null;
  78756. }
  78757. childImpostor.parent = mainImpostor;
  78758. childImpostor.resetUpdateFlags();
  78759. 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));
  78760. //Add the mass of the children.
  78761. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78762. }
  78763. }
  78764. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78765. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78766. };
  78767. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78768. }
  78769. };
  78770. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78771. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78772. this.world.removeEventListener("preStep", impostor.beforeStep);
  78773. this.world.removeEventListener("postStep", impostor.afterStep);
  78774. this.world.remove(impostor.physicsBody);
  78775. };
  78776. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78777. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78778. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78779. if (!mainBody || !connectedBody) {
  78780. return;
  78781. }
  78782. var constraint;
  78783. var jointData = impostorJoint.joint.jointData;
  78784. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78785. var constraintData = {
  78786. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78787. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78788. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78789. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78790. maxForce: jointData.nativeParams.maxForce,
  78791. collideConnected: !!jointData.collision
  78792. };
  78793. switch (impostorJoint.joint.type) {
  78794. case BABYLON.PhysicsJoint.HingeJoint:
  78795. case BABYLON.PhysicsJoint.Hinge2Joint:
  78796. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78797. break;
  78798. case BABYLON.PhysicsJoint.DistanceJoint:
  78799. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78800. break;
  78801. case BABYLON.PhysicsJoint.SpringJoint:
  78802. var springData = jointData;
  78803. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78804. restLength: springData.length,
  78805. stiffness: springData.stiffness,
  78806. damping: springData.damping,
  78807. localAnchorA: constraintData.pivotA,
  78808. localAnchorB: constraintData.pivotB
  78809. });
  78810. break;
  78811. case BABYLON.PhysicsJoint.LockJoint:
  78812. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78813. break;
  78814. case BABYLON.PhysicsJoint.PointToPointJoint:
  78815. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78816. default:
  78817. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78818. break;
  78819. }
  78820. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78821. constraint.collideConnected = !!jointData.collision;
  78822. impostorJoint.joint.physicsJoint = constraint;
  78823. //don't add spring as constraint, as it is not one.
  78824. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78825. this.world.addConstraint(constraint);
  78826. }
  78827. else {
  78828. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78829. constraint.applyForce();
  78830. });
  78831. }
  78832. };
  78833. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78834. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78835. };
  78836. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78837. var index;
  78838. var mat;
  78839. for (index = 0; index < this._physicsMaterials.length; index++) {
  78840. mat = this._physicsMaterials[index];
  78841. if (mat.friction === friction && mat.restitution === restitution) {
  78842. return mat;
  78843. }
  78844. }
  78845. var currentMat = new this.BJSCANNON.Material(name);
  78846. currentMat.friction = friction;
  78847. currentMat.restitution = restitution;
  78848. this._physicsMaterials.push(currentMat);
  78849. return currentMat;
  78850. };
  78851. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78852. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78853. };
  78854. CannonJSPlugin.prototype._createShape = function (impostor) {
  78855. var object = impostor.object;
  78856. var returnValue;
  78857. var extendSize = impostor.getObjectExtendSize();
  78858. switch (impostor.type) {
  78859. case BABYLON.PhysicsImpostor.SphereImpostor:
  78860. var radiusX = extendSize.x;
  78861. var radiusY = extendSize.y;
  78862. var radiusZ = extendSize.z;
  78863. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78864. break;
  78865. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78866. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78867. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78868. break;
  78869. case BABYLON.PhysicsImpostor.BoxImpostor:
  78870. var box = extendSize.scale(0.5);
  78871. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78872. break;
  78873. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78874. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78875. returnValue = new this.BJSCANNON.Plane();
  78876. break;
  78877. case BABYLON.PhysicsImpostor.MeshImpostor:
  78878. // should transform the vertex data to world coordinates!!
  78879. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78880. var rawFaces = object.getIndices ? object.getIndices() : [];
  78881. if (!rawVerts)
  78882. return;
  78883. // get only scale! so the object could transform correctly.
  78884. var oldPosition = object.position.clone();
  78885. var oldRotation = object.rotation && object.rotation.clone();
  78886. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78887. object.position.copyFromFloats(0, 0, 0);
  78888. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78889. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78890. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78891. var transform = object.computeWorldMatrix(true);
  78892. // convert rawVerts to object space
  78893. var temp = new Array();
  78894. var index;
  78895. for (index = 0; index < rawVerts.length; index += 3) {
  78896. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78897. }
  78898. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78899. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78900. //now set back the transformation!
  78901. object.position.copyFrom(oldPosition);
  78902. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78903. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78904. break;
  78905. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78906. var oldPosition2 = object.position.clone();
  78907. var oldRotation2 = object.rotation && object.rotation.clone();
  78908. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78909. object.position.copyFromFloats(0, 0, 0);
  78910. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78911. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78912. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78913. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78914. returnValue = this._createHeightmap(object);
  78915. object.position.copyFrom(oldPosition2);
  78916. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78917. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78918. object.computeWorldMatrix(true);
  78919. break;
  78920. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78921. returnValue = new this.BJSCANNON.Particle();
  78922. break;
  78923. }
  78924. return returnValue;
  78925. };
  78926. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78927. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78928. var transform = object.computeWorldMatrix(true);
  78929. // convert rawVerts to object space
  78930. var temp = new Array();
  78931. var index;
  78932. for (index = 0; index < pos.length; index += 3) {
  78933. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78934. }
  78935. pos = temp;
  78936. var matrix = new Array();
  78937. //For now pointDepth will not be used and will be automatically calculated.
  78938. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78939. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78940. var boundingInfo = object.getBoundingInfo();
  78941. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78942. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78943. var elementSize = dim * 2 / arraySize;
  78944. for (var i = 0; i < pos.length; i = i + 3) {
  78945. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78946. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78947. var y = -pos[i + 2] + minY;
  78948. if (!matrix[x]) {
  78949. matrix[x] = [];
  78950. }
  78951. if (!matrix[x][z]) {
  78952. matrix[x][z] = y;
  78953. }
  78954. matrix[x][z] = Math.max(y, matrix[x][z]);
  78955. }
  78956. for (var x = 0; x <= arraySize; ++x) {
  78957. if (!matrix[x]) {
  78958. var loc = 1;
  78959. while (!matrix[(x + loc) % arraySize]) {
  78960. loc++;
  78961. }
  78962. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78963. //console.log("missing x", x);
  78964. }
  78965. for (var z = 0; z <= arraySize; ++z) {
  78966. if (!matrix[x][z]) {
  78967. var loc = 1;
  78968. var newValue;
  78969. while (newValue === undefined) {
  78970. newValue = matrix[x][(z + loc++) % arraySize];
  78971. }
  78972. matrix[x][z] = newValue;
  78973. }
  78974. }
  78975. }
  78976. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78977. elementSize: elementSize
  78978. });
  78979. //For future reference, needed for body transformation
  78980. shape.minY = minY;
  78981. return shape;
  78982. };
  78983. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78984. var object = impostor.object;
  78985. //make sure it is updated...
  78986. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78987. // The delta between the mesh position and the mesh bounding box center
  78988. var bInfo = object.getBoundingInfo();
  78989. if (!bInfo)
  78990. return;
  78991. var center = impostor.getObjectCenter();
  78992. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78993. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78994. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78995. this._tmpPosition.copyFrom(center);
  78996. var quaternion = object.rotationQuaternion;
  78997. if (!quaternion) {
  78998. return;
  78999. }
  79000. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  79001. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  79002. //-90 DEG in X, precalculated
  79003. quaternion = quaternion.multiply(this._minus90X);
  79004. //Invert! (Precalculated, 90 deg in X)
  79005. //No need to clone. this will never change.
  79006. impostor.setDeltaRotation(this._plus90X);
  79007. }
  79008. //If it is a heightfield, if should be centered.
  79009. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  79010. var mesh = object;
  79011. var boundingInfo = mesh.getBoundingInfo();
  79012. //calculate the correct body position:
  79013. var rotationQuaternion = mesh.rotationQuaternion;
  79014. mesh.rotationQuaternion = this._tmpUnityRotation;
  79015. mesh.computeWorldMatrix(true);
  79016. //get original center with no rotation
  79017. var c = center.clone();
  79018. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  79019. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  79020. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  79021. mesh.setPreTransformMatrix(p);
  79022. mesh.computeWorldMatrix(true);
  79023. //calculate the translation
  79024. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  79025. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  79026. //add it inverted to the delta
  79027. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  79028. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  79029. //rotation is back
  79030. mesh.rotationQuaternion = rotationQuaternion;
  79031. mesh.setPreTransformMatrix(oldPivot);
  79032. mesh.computeWorldMatrix(true);
  79033. }
  79034. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  79035. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  79036. //this._tmpPosition.copyFrom(object.position);
  79037. }
  79038. impostor.setDeltaPosition(this._tmpDeltaPosition);
  79039. //Now update the impostor object
  79040. impostor.physicsBody.position.copy(this._tmpPosition);
  79041. impostor.physicsBody.quaternion.copy(quaternion);
  79042. };
  79043. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79044. impostor.object.position.copyFrom(impostor.physicsBody.position);
  79045. if (impostor.object.rotationQuaternion) {
  79046. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  79047. }
  79048. };
  79049. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79050. impostor.physicsBody.position.copy(newPosition);
  79051. impostor.physicsBody.quaternion.copy(newRotation);
  79052. };
  79053. CannonJSPlugin.prototype.isSupported = function () {
  79054. return this.BJSCANNON !== undefined;
  79055. };
  79056. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79057. impostor.physicsBody.velocity.copy(velocity);
  79058. };
  79059. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79060. impostor.physicsBody.angularVelocity.copy(velocity);
  79061. };
  79062. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79063. var v = impostor.physicsBody.velocity;
  79064. if (!v) {
  79065. return null;
  79066. }
  79067. return new BABYLON.Vector3(v.x, v.y, v.z);
  79068. };
  79069. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79070. var v = impostor.physicsBody.angularVelocity;
  79071. if (!v) {
  79072. return null;
  79073. }
  79074. return new BABYLON.Vector3(v.x, v.y, v.z);
  79075. };
  79076. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79077. impostor.physicsBody.mass = mass;
  79078. impostor.physicsBody.updateMassProperties();
  79079. };
  79080. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  79081. return impostor.physicsBody.mass;
  79082. };
  79083. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  79084. return impostor.physicsBody.material.friction;
  79085. };
  79086. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79087. impostor.physicsBody.material.friction = friction;
  79088. };
  79089. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79090. return impostor.physicsBody.material.restitution;
  79091. };
  79092. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79093. impostor.physicsBody.material.restitution = restitution;
  79094. };
  79095. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  79096. impostor.physicsBody.sleep();
  79097. };
  79098. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  79099. impostor.physicsBody.wakeUp();
  79100. };
  79101. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79102. joint.physicsJoint.distance = maxDistance;
  79103. };
  79104. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79105. // if (!motorIndex) {
  79106. // joint.physicsJoint.enableMotor();
  79107. // }
  79108. // }
  79109. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79110. // if (!motorIndex) {
  79111. // joint.physicsJoint.disableMotor();
  79112. // }
  79113. // }
  79114. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79115. if (!motorIndex) {
  79116. joint.physicsJoint.enableMotor();
  79117. joint.physicsJoint.setMotorSpeed(speed);
  79118. if (maxForce) {
  79119. this.setLimit(joint, maxForce);
  79120. }
  79121. }
  79122. };
  79123. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  79124. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  79125. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  79126. };
  79127. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79128. var body = impostor.physicsBody;
  79129. mesh.position.x = body.position.x;
  79130. mesh.position.y = body.position.y;
  79131. mesh.position.z = body.position.z;
  79132. if (mesh.rotationQuaternion) {
  79133. mesh.rotationQuaternion.x = body.quaternion.x;
  79134. mesh.rotationQuaternion.y = body.quaternion.y;
  79135. mesh.rotationQuaternion.z = body.quaternion.z;
  79136. mesh.rotationQuaternion.w = body.quaternion.w;
  79137. }
  79138. };
  79139. CannonJSPlugin.prototype.getRadius = function (impostor) {
  79140. var shape = impostor.physicsBody.shapes[0];
  79141. return shape.boundingSphereRadius;
  79142. };
  79143. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79144. var shape = impostor.physicsBody.shapes[0];
  79145. result.x = shape.halfExtents.x * 2;
  79146. result.y = shape.halfExtents.y * 2;
  79147. result.z = shape.halfExtents.z * 2;
  79148. };
  79149. CannonJSPlugin.prototype.dispose = function () {
  79150. };
  79151. CannonJSPlugin.prototype._extendNamespace = function () {
  79152. //this will force cannon to execute at least one step when using interpolation
  79153. var step_tmp1 = new this.BJSCANNON.Vec3();
  79154. var Engine = this.BJSCANNON;
  79155. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  79156. maxSubSteps = maxSubSteps || 10;
  79157. timeSinceLastCalled = timeSinceLastCalled || 0;
  79158. if (timeSinceLastCalled === 0) {
  79159. this.internalStep(dt);
  79160. this.time += dt;
  79161. }
  79162. else {
  79163. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  79164. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  79165. var t0 = performance.now();
  79166. for (var i = 0; i !== internalSteps; i++) {
  79167. this.internalStep(dt);
  79168. if (performance.now() - t0 > dt * 1000) {
  79169. break;
  79170. }
  79171. }
  79172. this.time += timeSinceLastCalled;
  79173. var h = this.time % dt;
  79174. var h_div_dt = h / dt;
  79175. var interpvelo = step_tmp1;
  79176. var bodies = this.bodies;
  79177. for (var j = 0; j !== bodies.length; j++) {
  79178. var b = bodies[j];
  79179. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  79180. b.position.vsub(b.previousPosition, interpvelo);
  79181. interpvelo.scale(h_div_dt, interpvelo);
  79182. b.position.vadd(interpvelo, b.interpolatedPosition);
  79183. }
  79184. else {
  79185. b.interpolatedPosition.copy(b.position);
  79186. b.interpolatedQuaternion.copy(b.quaternion);
  79187. }
  79188. }
  79189. }
  79190. };
  79191. };
  79192. return CannonJSPlugin;
  79193. }());
  79194. BABYLON.CannonJSPlugin = CannonJSPlugin;
  79195. })(BABYLON || (BABYLON = {}));
  79196. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  79197. "use strict";
  79198. var BABYLON;
  79199. (function (BABYLON) {
  79200. var OimoJSPlugin = /** @class */ (function () {
  79201. function OimoJSPlugin(iterations) {
  79202. this.name = "OimoJSPlugin";
  79203. this._tmpImpostorsArray = [];
  79204. this._tmpPositionVector = BABYLON.Vector3.Zero();
  79205. this.BJSOIMO = OIMO;
  79206. this.world = new this.BJSOIMO.World({
  79207. iterations: iterations
  79208. });
  79209. this.world.clear();
  79210. }
  79211. OimoJSPlugin.prototype.setGravity = function (gravity) {
  79212. this.world.gravity.copy(gravity);
  79213. };
  79214. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  79215. this.world.timeStep = timeStep;
  79216. };
  79217. OimoJSPlugin.prototype.getTimeStep = function () {
  79218. return this.world.timeStep;
  79219. };
  79220. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  79221. var _this = this;
  79222. impostors.forEach(function (impostor) {
  79223. impostor.beforeStep();
  79224. });
  79225. this.world.step();
  79226. impostors.forEach(function (impostor) {
  79227. impostor.afterStep();
  79228. //update the ordered impostors array
  79229. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  79230. });
  79231. //check for collisions
  79232. var contact = this.world.contacts;
  79233. while (contact !== null) {
  79234. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  79235. contact = contact.next;
  79236. continue;
  79237. }
  79238. //is this body colliding with any other? get the impostor
  79239. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  79240. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  79241. if (!mainImpostor || !collidingImpostor) {
  79242. contact = contact.next;
  79243. continue;
  79244. }
  79245. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  79246. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  79247. contact = contact.next;
  79248. }
  79249. };
  79250. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79251. var mass = impostor.physicsBody.mass;
  79252. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  79253. };
  79254. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79255. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  79256. this.applyImpulse(impostor, force, contactPoint);
  79257. };
  79258. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79259. var _this = this;
  79260. //parent-child relationship. Does this impostor has a parent impostor?
  79261. if (impostor.parent) {
  79262. if (impostor.physicsBody) {
  79263. this.removePhysicsBody(impostor);
  79264. //TODO is that needed?
  79265. impostor.forceUpdate();
  79266. }
  79267. return;
  79268. }
  79269. if (impostor.isBodyInitRequired()) {
  79270. var bodyConfig = {
  79271. name: impostor.uniqueId,
  79272. //Oimo must have mass, also for static objects.
  79273. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  79274. size: [],
  79275. type: [],
  79276. pos: [],
  79277. posShape: [],
  79278. rot: [],
  79279. rotShape: [],
  79280. move: impostor.getParam("mass") !== 0,
  79281. density: impostor.getParam("mass"),
  79282. friction: impostor.getParam("friction"),
  79283. restitution: impostor.getParam("restitution"),
  79284. //Supporting older versions of Oimo
  79285. world: this.world
  79286. };
  79287. var impostors = [impostor];
  79288. var addToArray = function (parent) {
  79289. if (!parent.getChildMeshes)
  79290. return;
  79291. parent.getChildMeshes().forEach(function (m) {
  79292. if (m.physicsImpostor) {
  79293. impostors.push(m.physicsImpostor);
  79294. //m.physicsImpostor._init();
  79295. }
  79296. });
  79297. };
  79298. addToArray(impostor.object);
  79299. var checkWithEpsilon_1 = function (value) {
  79300. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  79301. };
  79302. impostors.forEach(function (i) {
  79303. if (!i.object.rotationQuaternion) {
  79304. return;
  79305. }
  79306. //get the correct bounding box
  79307. var oldQuaternion = i.object.rotationQuaternion;
  79308. var rot = oldQuaternion.toEulerAngles();
  79309. var extendSize = i.getObjectExtendSize();
  79310. var radToDeg = 57.295779513082320876;
  79311. if (i === impostor) {
  79312. var center = impostor.getObjectCenter();
  79313. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79314. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79315. //Can also use Array.prototype.push.apply
  79316. bodyConfig.pos.push(center.x);
  79317. bodyConfig.pos.push(center.y);
  79318. bodyConfig.pos.push(center.z);
  79319. bodyConfig.posShape.push(0, 0, 0);
  79320. //tmp solution
  79321. bodyConfig.rot.push(rot.x * radToDeg);
  79322. bodyConfig.rot.push(rot.y * radToDeg);
  79323. bodyConfig.rot.push(rot.z * radToDeg);
  79324. bodyConfig.rotShape.push(0, 0, 0);
  79325. }
  79326. else {
  79327. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79328. bodyConfig.posShape.push(localPosition.x);
  79329. bodyConfig.posShape.push(localPosition.y);
  79330. bodyConfig.posShape.push(localPosition.z);
  79331. bodyConfig.pos.push(0, 0, 0);
  79332. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79333. bodyConfig.rot.push(0);
  79334. bodyConfig.rot.push(0);
  79335. bodyConfig.rot.push(0);
  79336. bodyConfig.rotShape.push(rot.x * radToDeg);
  79337. bodyConfig.rotShape.push(rot.y * radToDeg);
  79338. bodyConfig.rotShape.push(rot.z * radToDeg);
  79339. }
  79340. // register mesh
  79341. switch (i.type) {
  79342. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79343. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79344. case BABYLON.PhysicsImpostor.SphereImpostor:
  79345. var radiusX = extendSize.x;
  79346. var radiusY = extendSize.y;
  79347. var radiusZ = extendSize.z;
  79348. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79349. bodyConfig.type.push('sphere');
  79350. //due to the way oimo works with compounds, add 3 times
  79351. bodyConfig.size.push(size);
  79352. bodyConfig.size.push(size);
  79353. bodyConfig.size.push(size);
  79354. break;
  79355. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79356. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79357. var sizeY = checkWithEpsilon_1(extendSize.y);
  79358. bodyConfig.type.push('cylinder');
  79359. bodyConfig.size.push(sizeX);
  79360. bodyConfig.size.push(sizeY);
  79361. //due to the way oimo works with compounds, add one more value.
  79362. bodyConfig.size.push(sizeY);
  79363. break;
  79364. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79365. case BABYLON.PhysicsImpostor.BoxImpostor:
  79366. default:
  79367. var sizeX = checkWithEpsilon_1(extendSize.x);
  79368. var sizeY = checkWithEpsilon_1(extendSize.y);
  79369. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79370. bodyConfig.type.push('box');
  79371. //if (i === impostor) {
  79372. bodyConfig.size.push(sizeX);
  79373. bodyConfig.size.push(sizeY);
  79374. bodyConfig.size.push(sizeZ);
  79375. //} else {
  79376. // bodyConfig.size.push(0,0,0);
  79377. //}
  79378. break;
  79379. }
  79380. //actually not needed, but hey...
  79381. i.object.rotationQuaternion = oldQuaternion;
  79382. });
  79383. impostor.physicsBody = this.world.add(bodyConfig);
  79384. }
  79385. else {
  79386. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79387. }
  79388. impostor.setDeltaPosition(this._tmpPositionVector);
  79389. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79390. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79391. };
  79392. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79393. //impostor.physicsBody.dispose();
  79394. //Same as : (older oimo versions)
  79395. this.world.removeRigidBody(impostor.physicsBody);
  79396. };
  79397. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79398. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79399. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79400. if (!mainBody || !connectedBody) {
  79401. return;
  79402. }
  79403. var jointData = impostorJoint.joint.jointData;
  79404. var options = jointData.nativeParams || {};
  79405. var type;
  79406. var nativeJointData = {
  79407. body1: mainBody,
  79408. body2: connectedBody,
  79409. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79410. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79411. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79412. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79413. min: options.min,
  79414. max: options.max,
  79415. collision: options.collision || jointData.collision,
  79416. spring: options.spring,
  79417. //supporting older version of Oimo
  79418. world: this.world
  79419. };
  79420. switch (impostorJoint.joint.type) {
  79421. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79422. type = "jointBall";
  79423. break;
  79424. case BABYLON.PhysicsJoint.SpringJoint:
  79425. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79426. var springData = jointData;
  79427. nativeJointData.min = springData.length || nativeJointData.min;
  79428. //Max should also be set, just make sure it is at least min
  79429. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79430. case BABYLON.PhysicsJoint.DistanceJoint:
  79431. type = "jointDistance";
  79432. nativeJointData.max = jointData.maxDistance;
  79433. break;
  79434. case BABYLON.PhysicsJoint.PrismaticJoint:
  79435. type = "jointPrisme";
  79436. break;
  79437. case BABYLON.PhysicsJoint.SliderJoint:
  79438. type = "jointSlide";
  79439. break;
  79440. case BABYLON.PhysicsJoint.WheelJoint:
  79441. type = "jointWheel";
  79442. break;
  79443. case BABYLON.PhysicsJoint.HingeJoint:
  79444. default:
  79445. type = "jointHinge";
  79446. break;
  79447. }
  79448. nativeJointData.type = type;
  79449. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79450. };
  79451. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79452. //Bug in Oimo prevents us from disposing a joint in the playground
  79453. //joint.joint.physicsJoint.dispose();
  79454. //So we will bruteforce it!
  79455. try {
  79456. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79457. }
  79458. catch (e) {
  79459. BABYLON.Tools.Warn(e);
  79460. }
  79461. };
  79462. OimoJSPlugin.prototype.isSupported = function () {
  79463. return this.BJSOIMO !== undefined;
  79464. };
  79465. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79466. if (!impostor.physicsBody.sleeping) {
  79467. //TODO check that
  79468. /*if (impostor.physicsBody.shapes.next) {
  79469. var parentShape = this._getLastShape(impostor.physicsBody);
  79470. impostor.object.position.copyFrom(parentShape.position);
  79471. console.log(parentShape.position);
  79472. } else {*/
  79473. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79474. //}
  79475. if (impostor.object.rotationQuaternion) {
  79476. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79477. }
  79478. }
  79479. };
  79480. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79481. var body = impostor.physicsBody;
  79482. body.position.copy(newPosition);
  79483. body.orientation.copy(newRotation);
  79484. body.syncShapes();
  79485. body.awake();
  79486. };
  79487. /*private _getLastShape(body: any): any {
  79488. var lastShape = body.shapes;
  79489. while (lastShape.next) {
  79490. lastShape = lastShape.next;
  79491. }
  79492. return lastShape;
  79493. }*/
  79494. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79495. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79496. };
  79497. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79498. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79499. };
  79500. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79501. var v = impostor.physicsBody.linearVelocity;
  79502. if (!v) {
  79503. return null;
  79504. }
  79505. return new BABYLON.Vector3(v.x, v.y, v.z);
  79506. };
  79507. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79508. var v = impostor.physicsBody.angularVelocity;
  79509. if (!v) {
  79510. return null;
  79511. }
  79512. return new BABYLON.Vector3(v.x, v.y, v.z);
  79513. };
  79514. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79515. var staticBody = mass === 0;
  79516. //this will actually set the body's density and not its mass.
  79517. //But this is how oimo treats the mass variable.
  79518. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79519. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79520. };
  79521. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79522. return impostor.physicsBody.shapes.density;
  79523. };
  79524. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79525. return impostor.physicsBody.shapes.friction;
  79526. };
  79527. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79528. impostor.physicsBody.shapes.friction = friction;
  79529. };
  79530. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79531. return impostor.physicsBody.shapes.restitution;
  79532. };
  79533. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79534. impostor.physicsBody.shapes.restitution = restitution;
  79535. };
  79536. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79537. impostor.physicsBody.sleep();
  79538. };
  79539. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79540. impostor.physicsBody.awake();
  79541. };
  79542. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79543. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79544. if (minDistance !== void 0) {
  79545. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79546. }
  79547. };
  79548. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79549. //TODO separate rotational and transational motors.
  79550. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79551. if (motor) {
  79552. motor.setMotor(speed, maxForce);
  79553. }
  79554. };
  79555. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79556. //TODO separate rotational and transational motors.
  79557. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79558. if (motor) {
  79559. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79560. }
  79561. };
  79562. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79563. var body = impostor.physicsBody;
  79564. mesh.position.x = body.position.x;
  79565. mesh.position.y = body.position.y;
  79566. mesh.position.z = body.position.z;
  79567. if (mesh.rotationQuaternion) {
  79568. mesh.rotationQuaternion.x = body.orientation.x;
  79569. mesh.rotationQuaternion.y = body.orientation.y;
  79570. mesh.rotationQuaternion.z = body.orientation.z;
  79571. mesh.rotationQuaternion.w = body.orientation.s;
  79572. }
  79573. };
  79574. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79575. return impostor.physicsBody.shapes.radius;
  79576. };
  79577. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79578. var shape = impostor.physicsBody.shapes;
  79579. result.x = shape.halfWidth * 2;
  79580. result.y = shape.halfHeight * 2;
  79581. result.z = shape.halfDepth * 2;
  79582. };
  79583. OimoJSPlugin.prototype.dispose = function () {
  79584. this.world.clear();
  79585. };
  79586. return OimoJSPlugin;
  79587. }());
  79588. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79589. })(BABYLON || (BABYLON = {}));
  79590. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79591. "use strict";
  79592. var BABYLON;
  79593. (function (BABYLON) {
  79594. /*
  79595. * Based on jsTGALoader - Javascript loader for TGA file
  79596. * By Vincent Thibault
  79597. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79598. */
  79599. var TGATools = /** @class */ (function () {
  79600. function TGATools() {
  79601. }
  79602. TGATools.GetTGAHeader = function (data) {
  79603. var offset = 0;
  79604. var header = {
  79605. id_length: data[offset++],
  79606. colormap_type: data[offset++],
  79607. image_type: data[offset++],
  79608. colormap_index: data[offset++] | data[offset++] << 8,
  79609. colormap_length: data[offset++] | data[offset++] << 8,
  79610. colormap_size: data[offset++],
  79611. origin: [
  79612. data[offset++] | data[offset++] << 8,
  79613. data[offset++] | data[offset++] << 8
  79614. ],
  79615. width: data[offset++] | data[offset++] << 8,
  79616. height: data[offset++] | data[offset++] << 8,
  79617. pixel_size: data[offset++],
  79618. flags: data[offset++]
  79619. };
  79620. return header;
  79621. };
  79622. TGATools.UploadContent = function (gl, data) {
  79623. // Not enough data to contain header ?
  79624. if (data.length < 19) {
  79625. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79626. return;
  79627. }
  79628. // Read Header
  79629. var offset = 18;
  79630. var header = TGATools.GetTGAHeader(data);
  79631. // Assume it's a valid Targa file.
  79632. if (header.id_length + offset > data.length) {
  79633. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79634. return;
  79635. }
  79636. // Skip not needed data
  79637. offset += header.id_length;
  79638. var use_rle = false;
  79639. var use_pal = false;
  79640. var use_grey = false;
  79641. // Get some informations.
  79642. switch (header.image_type) {
  79643. case TGATools._TYPE_RLE_INDEXED:
  79644. use_rle = true;
  79645. case TGATools._TYPE_INDEXED:
  79646. use_pal = true;
  79647. break;
  79648. case TGATools._TYPE_RLE_RGB:
  79649. use_rle = true;
  79650. case TGATools._TYPE_RGB:
  79651. // use_rgb = true;
  79652. break;
  79653. case TGATools._TYPE_RLE_GREY:
  79654. use_rle = true;
  79655. case TGATools._TYPE_GREY:
  79656. use_grey = true;
  79657. break;
  79658. }
  79659. var pixel_data;
  79660. // var numAlphaBits = header.flags & 0xf;
  79661. var pixel_size = header.pixel_size >> 3;
  79662. var pixel_total = header.width * header.height * pixel_size;
  79663. // Read palettes
  79664. var palettes;
  79665. if (use_pal) {
  79666. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79667. }
  79668. // Read LRE
  79669. if (use_rle) {
  79670. pixel_data = new Uint8Array(pixel_total);
  79671. var c, count, i;
  79672. var localOffset = 0;
  79673. var pixels = new Uint8Array(pixel_size);
  79674. while (offset < pixel_total && localOffset < pixel_total) {
  79675. c = data[offset++];
  79676. count = (c & 0x7f) + 1;
  79677. // RLE pixels
  79678. if (c & 0x80) {
  79679. // Bind pixel tmp array
  79680. for (i = 0; i < pixel_size; ++i) {
  79681. pixels[i] = data[offset++];
  79682. }
  79683. // Copy pixel array
  79684. for (i = 0; i < count; ++i) {
  79685. pixel_data.set(pixels, localOffset + i * pixel_size);
  79686. }
  79687. localOffset += pixel_size * count;
  79688. }
  79689. else {
  79690. count *= pixel_size;
  79691. for (i = 0; i < count; ++i) {
  79692. pixel_data[localOffset + i] = data[offset++];
  79693. }
  79694. localOffset += count;
  79695. }
  79696. }
  79697. }
  79698. else {
  79699. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79700. }
  79701. // Load to texture
  79702. var x_start, y_start, x_step, y_step, y_end, x_end;
  79703. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79704. default:
  79705. case TGATools._ORIGIN_UL:
  79706. x_start = 0;
  79707. x_step = 1;
  79708. x_end = header.width;
  79709. y_start = 0;
  79710. y_step = 1;
  79711. y_end = header.height;
  79712. break;
  79713. case TGATools._ORIGIN_BL:
  79714. x_start = 0;
  79715. x_step = 1;
  79716. x_end = header.width;
  79717. y_start = header.height - 1;
  79718. y_step = -1;
  79719. y_end = -1;
  79720. break;
  79721. case TGATools._ORIGIN_UR:
  79722. x_start = header.width - 1;
  79723. x_step = -1;
  79724. x_end = -1;
  79725. y_start = 0;
  79726. y_step = 1;
  79727. y_end = header.height;
  79728. break;
  79729. case TGATools._ORIGIN_BR:
  79730. x_start = header.width - 1;
  79731. x_step = -1;
  79732. x_end = -1;
  79733. y_start = header.height - 1;
  79734. y_step = -1;
  79735. y_end = -1;
  79736. break;
  79737. }
  79738. // Load the specify method
  79739. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79740. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79741. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79742. };
  79743. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79744. var image = pixel_data, colormap = palettes;
  79745. var width = header.width, height = header.height;
  79746. var color, i = 0, x, y;
  79747. var imageData = new Uint8Array(width * height * 4);
  79748. for (y = y_start; y !== y_end; y += y_step) {
  79749. for (x = x_start; x !== x_end; x += x_step, i++) {
  79750. color = image[i];
  79751. imageData[(x + width * y) * 4 + 3] = 255;
  79752. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79753. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79754. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79755. }
  79756. }
  79757. return imageData;
  79758. };
  79759. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79760. var image = pixel_data;
  79761. var width = header.width, height = header.height;
  79762. var color, i = 0, x, y;
  79763. var imageData = new Uint8Array(width * height * 4);
  79764. for (y = y_start; y !== y_end; y += y_step) {
  79765. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79766. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79767. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79768. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79769. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79770. imageData[(x + width * y) * 4 + 0] = r;
  79771. imageData[(x + width * y) * 4 + 1] = g;
  79772. imageData[(x + width * y) * 4 + 2] = b;
  79773. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79774. }
  79775. }
  79776. return imageData;
  79777. };
  79778. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79779. var image = pixel_data;
  79780. var width = header.width, height = header.height;
  79781. var i = 0, x, y;
  79782. var imageData = new Uint8Array(width * height * 4);
  79783. for (y = y_start; y !== y_end; y += y_step) {
  79784. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79785. imageData[(x + width * y) * 4 + 3] = 255;
  79786. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79787. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79788. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79789. }
  79790. }
  79791. return imageData;
  79792. };
  79793. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79794. var image = pixel_data;
  79795. var width = header.width, height = header.height;
  79796. var i = 0, x, y;
  79797. var imageData = new Uint8Array(width * height * 4);
  79798. for (y = y_start; y !== y_end; y += y_step) {
  79799. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79800. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79801. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79802. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79803. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79804. }
  79805. }
  79806. return imageData;
  79807. };
  79808. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79809. var image = pixel_data;
  79810. var width = header.width, height = header.height;
  79811. var color, i = 0, x, y;
  79812. var imageData = new Uint8Array(width * height * 4);
  79813. for (y = y_start; y !== y_end; y += y_step) {
  79814. for (x = x_start; x !== x_end; x += x_step, i++) {
  79815. color = image[i];
  79816. imageData[(x + width * y) * 4 + 0] = color;
  79817. imageData[(x + width * y) * 4 + 1] = color;
  79818. imageData[(x + width * y) * 4 + 2] = color;
  79819. imageData[(x + width * y) * 4 + 3] = 255;
  79820. }
  79821. }
  79822. return imageData;
  79823. };
  79824. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79825. var image = pixel_data;
  79826. var width = header.width, height = header.height;
  79827. var i = 0, x, y;
  79828. var imageData = new Uint8Array(width * height * 4);
  79829. for (y = y_start; y !== y_end; y += y_step) {
  79830. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79831. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79832. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79833. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79834. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79835. }
  79836. }
  79837. return imageData;
  79838. };
  79839. //private static _TYPE_NO_DATA = 0;
  79840. TGATools._TYPE_INDEXED = 1;
  79841. TGATools._TYPE_RGB = 2;
  79842. TGATools._TYPE_GREY = 3;
  79843. TGATools._TYPE_RLE_INDEXED = 9;
  79844. TGATools._TYPE_RLE_RGB = 10;
  79845. TGATools._TYPE_RLE_GREY = 11;
  79846. TGATools._ORIGIN_MASK = 0x30;
  79847. TGATools._ORIGIN_SHIFT = 0x04;
  79848. TGATools._ORIGIN_BL = 0x00;
  79849. TGATools._ORIGIN_BR = 0x01;
  79850. TGATools._ORIGIN_UL = 0x02;
  79851. TGATools._ORIGIN_UR = 0x03;
  79852. return TGATools;
  79853. }());
  79854. BABYLON.TGATools = TGATools;
  79855. })(BABYLON || (BABYLON = {}));
  79856. //# sourceMappingURL=babylon.tga.js.map
  79857. "use strict";
  79858. var BABYLON;
  79859. (function (BABYLON) {
  79860. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79861. // All values and structures referenced from:
  79862. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79863. var DDS_MAGIC = 0x20534444;
  79864. var
  79865. //DDSD_CAPS = 0x1,
  79866. //DDSD_HEIGHT = 0x2,
  79867. //DDSD_WIDTH = 0x4,
  79868. //DDSD_PITCH = 0x8,
  79869. //DDSD_PIXELFORMAT = 0x1000,
  79870. DDSD_MIPMAPCOUNT = 0x20000;
  79871. //DDSD_LINEARSIZE = 0x80000,
  79872. //DDSD_DEPTH = 0x800000;
  79873. // var DDSCAPS_COMPLEX = 0x8,
  79874. // DDSCAPS_MIPMAP = 0x400000,
  79875. // DDSCAPS_TEXTURE = 0x1000;
  79876. var DDSCAPS2_CUBEMAP = 0x200;
  79877. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79878. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79879. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79880. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79881. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79882. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79883. // DDSCAPS2_VOLUME = 0x200000;
  79884. var
  79885. //DDPF_ALPHAPIXELS = 0x1,
  79886. //DDPF_ALPHA = 0x2,
  79887. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79888. //DDPF_YUV = 0x200,
  79889. DDPF_LUMINANCE = 0x20000;
  79890. function FourCCToInt32(value) {
  79891. return value.charCodeAt(0) +
  79892. (value.charCodeAt(1) << 8) +
  79893. (value.charCodeAt(2) << 16) +
  79894. (value.charCodeAt(3) << 24);
  79895. }
  79896. function Int32ToFourCC(value) {
  79897. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79898. }
  79899. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79900. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79901. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79902. var FOURCC_DX10 = FourCCToInt32("DX10");
  79903. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79904. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79905. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79906. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79907. var headerLengthInt = 31; // The header length in 32 bit ints
  79908. // Offsets into the header array
  79909. var off_magic = 0;
  79910. var off_size = 1;
  79911. var off_flags = 2;
  79912. var off_height = 3;
  79913. var off_width = 4;
  79914. var off_mipmapCount = 7;
  79915. var off_pfFlags = 20;
  79916. var off_pfFourCC = 21;
  79917. var off_RGBbpp = 22;
  79918. var off_RMask = 23;
  79919. var off_GMask = 24;
  79920. var off_BMask = 25;
  79921. var off_AMask = 26;
  79922. // var off_caps1 = 27;
  79923. var off_caps2 = 28;
  79924. // var off_caps3 = 29;
  79925. // var off_caps4 = 30;
  79926. var off_dxgiFormat = 32;
  79927. ;
  79928. var DDSTools = /** @class */ (function () {
  79929. function DDSTools() {
  79930. }
  79931. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79932. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79933. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79934. var mipmapCount = 1;
  79935. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79936. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79937. }
  79938. var fourCC = header[off_pfFourCC];
  79939. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79940. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79941. switch (fourCC) {
  79942. case FOURCC_D3DFMT_R16G16B16A16F:
  79943. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79944. break;
  79945. case FOURCC_D3DFMT_R32G32B32A32F:
  79946. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79947. break;
  79948. case FOURCC_DX10:
  79949. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79950. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79951. break;
  79952. }
  79953. }
  79954. return {
  79955. width: header[off_width],
  79956. height: header[off_height],
  79957. mipmapCount: mipmapCount,
  79958. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79959. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79960. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79961. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79962. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79963. dxgiFormat: dxgiFormat,
  79964. textureType: textureType
  79965. };
  79966. };
  79967. DDSTools._ToHalfFloat = function (value) {
  79968. if (!DDSTools._FloatView) {
  79969. DDSTools._FloatView = new Float32Array(1);
  79970. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79971. }
  79972. DDSTools._FloatView[0] = value;
  79973. var x = DDSTools._Int32View[0];
  79974. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79975. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79976. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79977. /* If zero, or denormal, or exponent underflows too much for a denormal
  79978. * half, return signed zero. */
  79979. if (e < 103) {
  79980. return bits;
  79981. }
  79982. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79983. if (e > 142) {
  79984. bits |= 0x7c00;
  79985. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79986. * not Inf, so make sure we set one mantissa bit too. */
  79987. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79988. return bits;
  79989. }
  79990. /* If exponent underflows but not too much, return a denormal */
  79991. if (e < 113) {
  79992. m |= 0x0800;
  79993. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79994. * to 1, which is OK. */
  79995. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79996. return bits;
  79997. }
  79998. bits |= ((e - 112) << 10) | (m >> 1);
  79999. bits += m & 1;
  80000. return bits;
  80001. };
  80002. DDSTools._FromHalfFloat = function (value) {
  80003. var s = (value & 0x8000) >> 15;
  80004. var e = (value & 0x7C00) >> 10;
  80005. var f = value & 0x03FF;
  80006. if (e === 0) {
  80007. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  80008. }
  80009. else if (e == 0x1F) {
  80010. return f ? NaN : ((s ? -1 : 1) * Infinity);
  80011. }
  80012. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  80013. };
  80014. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80015. var destArray = new Float32Array(dataLength);
  80016. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80017. var index = 0;
  80018. for (var y = 0; y < height; y++) {
  80019. for (var x = 0; x < width; x++) {
  80020. var srcPos = (x + y * width) * 4;
  80021. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  80022. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  80023. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  80024. if (DDSTools.StoreLODInAlphaChannel) {
  80025. destArray[index + 3] = lod;
  80026. }
  80027. else {
  80028. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  80029. }
  80030. index += 4;
  80031. }
  80032. }
  80033. return destArray;
  80034. };
  80035. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80036. if (DDSTools.StoreLODInAlphaChannel) {
  80037. var destArray = new Uint16Array(dataLength);
  80038. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80039. var index = 0;
  80040. for (var y = 0; y < height; y++) {
  80041. for (var x = 0; x < width; x++) {
  80042. var srcPos = (x + y * width) * 4;
  80043. destArray[index] = srcData[srcPos];
  80044. destArray[index + 1] = srcData[srcPos + 1];
  80045. destArray[index + 2] = srcData[srcPos + 2];
  80046. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  80047. index += 4;
  80048. }
  80049. }
  80050. return destArray;
  80051. }
  80052. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  80053. };
  80054. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80055. if (DDSTools.StoreLODInAlphaChannel) {
  80056. var destArray = new Float32Array(dataLength);
  80057. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80058. var index = 0;
  80059. for (var y = 0; y < height; y++) {
  80060. for (var x = 0; x < width; x++) {
  80061. var srcPos = (x + y * width) * 4;
  80062. destArray[index] = srcData[srcPos];
  80063. destArray[index + 1] = srcData[srcPos + 1];
  80064. destArray[index + 2] = srcData[srcPos + 2];
  80065. destArray[index + 3] = lod;
  80066. index += 4;
  80067. }
  80068. }
  80069. return destArray;
  80070. }
  80071. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  80072. };
  80073. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80074. var destArray = new Uint8Array(dataLength);
  80075. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80076. var index = 0;
  80077. for (var y = 0; y < height; y++) {
  80078. for (var x = 0; x < width; x++) {
  80079. var srcPos = (x + y * width) * 4;
  80080. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  80081. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  80082. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  80083. if (DDSTools.StoreLODInAlphaChannel) {
  80084. destArray[index + 3] = lod;
  80085. }
  80086. else {
  80087. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  80088. }
  80089. index += 4;
  80090. }
  80091. }
  80092. return destArray;
  80093. };
  80094. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80095. var destArray = new Uint8Array(dataLength);
  80096. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80097. var index = 0;
  80098. for (var y = 0; y < height; y++) {
  80099. for (var x = 0; x < width; x++) {
  80100. var srcPos = (x + y * width) * 4;
  80101. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  80102. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  80103. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  80104. if (DDSTools.StoreLODInAlphaChannel) {
  80105. destArray[index + 3] = lod;
  80106. }
  80107. else {
  80108. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  80109. }
  80110. index += 4;
  80111. }
  80112. }
  80113. return destArray;
  80114. };
  80115. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  80116. var byteArray = new Uint8Array(dataLength);
  80117. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80118. var index = 0;
  80119. for (var y = 0; y < height; y++) {
  80120. for (var x = 0; x < width; x++) {
  80121. var srcPos = (x + y * width) * 4;
  80122. byteArray[index] = srcData[srcPos + rOffset];
  80123. byteArray[index + 1] = srcData[srcPos + gOffset];
  80124. byteArray[index + 2] = srcData[srcPos + bOffset];
  80125. byteArray[index + 3] = srcData[srcPos + aOffset];
  80126. index += 4;
  80127. }
  80128. }
  80129. return byteArray;
  80130. };
  80131. DDSTools._ExtractLongWordOrder = function (value) {
  80132. if (value === 0 || value === 255 || value === -16777216) {
  80133. return 0;
  80134. }
  80135. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  80136. };
  80137. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  80138. var byteArray = new Uint8Array(dataLength);
  80139. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80140. var index = 0;
  80141. for (var y = 0; y < height; y++) {
  80142. for (var x = 0; x < width; x++) {
  80143. var srcPos = (x + y * width) * 3;
  80144. byteArray[index] = srcData[srcPos + rOffset];
  80145. byteArray[index + 1] = srcData[srcPos + gOffset];
  80146. byteArray[index + 2] = srcData[srcPos + bOffset];
  80147. index += 3;
  80148. }
  80149. }
  80150. return byteArray;
  80151. };
  80152. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  80153. var byteArray = new Uint8Array(dataLength);
  80154. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80155. var index = 0;
  80156. for (var y = 0; y < height; y++) {
  80157. for (var x = 0; x < width; x++) {
  80158. var srcPos = (x + y * width);
  80159. byteArray[index] = srcData[srcPos];
  80160. index++;
  80161. }
  80162. }
  80163. return byteArray;
  80164. };
  80165. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  80166. if (lodIndex === void 0) { lodIndex = -1; }
  80167. var ext = engine.getCaps().s3tc;
  80168. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80169. var fourCC, width, height, dataLength = 0, dataOffset;
  80170. var byteArray, mipmapCount, mip;
  80171. var internalFormat = 0;
  80172. var format = 0;
  80173. var blockBytes = 1;
  80174. if (header[off_magic] !== DDS_MAGIC) {
  80175. BABYLON.Tools.Error("Invalid magic number in DDS header");
  80176. return;
  80177. }
  80178. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  80179. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  80180. return;
  80181. }
  80182. if (info.isCompressed && !ext) {
  80183. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  80184. return;
  80185. }
  80186. var bpp = header[off_RGBbpp];
  80187. dataOffset = header[off_size] + 4;
  80188. var computeFormats = false;
  80189. if (info.isFourCC) {
  80190. fourCC = header[off_pfFourCC];
  80191. switch (fourCC) {
  80192. case FOURCC_DXT1:
  80193. blockBytes = 8;
  80194. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  80195. break;
  80196. case FOURCC_DXT3:
  80197. blockBytes = 16;
  80198. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  80199. break;
  80200. case FOURCC_DXT5:
  80201. blockBytes = 16;
  80202. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  80203. break;
  80204. case FOURCC_D3DFMT_R16G16B16A16F:
  80205. computeFormats = true;
  80206. break;
  80207. case FOURCC_D3DFMT_R32G32B32A32F:
  80208. computeFormats = true;
  80209. break;
  80210. case FOURCC_DX10:
  80211. // There is an additionnal header so dataOffset need to be changed
  80212. dataOffset += 5 * 4; // 5 uints
  80213. var supported = false;
  80214. switch (info.dxgiFormat) {
  80215. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  80216. computeFormats = true;
  80217. supported = true;
  80218. break;
  80219. case DXGI_FORMAT_B8G8R8X8_UNORM:
  80220. info.isRGB = true;
  80221. info.isFourCC = false;
  80222. bpp = 32;
  80223. supported = true;
  80224. break;
  80225. }
  80226. if (supported) {
  80227. break;
  80228. }
  80229. default:
  80230. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  80231. return;
  80232. }
  80233. }
  80234. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  80235. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  80236. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  80237. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  80238. if (computeFormats) {
  80239. format = engine._getWebGLTextureType(info.textureType);
  80240. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80241. }
  80242. mipmapCount = 1;
  80243. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  80244. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80245. }
  80246. for (var face = 0; face < faces; face++) {
  80247. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  80248. width = header[off_width];
  80249. height = header[off_height];
  80250. for (mip = 0; mip < mipmapCount; ++mip) {
  80251. if (lodIndex === -1 || lodIndex === mip) {
  80252. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  80253. var i = (lodIndex === -1) ? mip : 0;
  80254. if (!info.isCompressed && info.isFourCC) {
  80255. dataLength = width * height * 4;
  80256. var floatArray = null;
  80257. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  80258. if (bpp === 128) {
  80259. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80260. }
  80261. else if (bpp === 64) {
  80262. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80263. }
  80264. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80265. format = engine._getWebGLTextureType(info.textureType);
  80266. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80267. }
  80268. else {
  80269. if (bpp === 128) {
  80270. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80271. }
  80272. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  80273. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80274. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80275. format = engine._getWebGLTextureType(info.textureType);
  80276. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80277. }
  80278. else {
  80279. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80280. }
  80281. }
  80282. if (floatArray) {
  80283. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  80284. }
  80285. }
  80286. else if (info.isRGB) {
  80287. if (bpp === 24) {
  80288. dataLength = width * height * 3;
  80289. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  80290. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  80291. }
  80292. else {
  80293. dataLength = width * height * 4;
  80294. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  80295. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  80296. }
  80297. }
  80298. else if (info.isLuminance) {
  80299. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  80300. var unpaddedRowSize = width;
  80301. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  80302. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  80303. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  80304. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  80305. }
  80306. else {
  80307. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  80308. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  80309. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  80310. }
  80311. }
  80312. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80313. width *= 0.5;
  80314. height *= 0.5;
  80315. width = Math.max(1.0, width);
  80316. height = Math.max(1.0, height);
  80317. }
  80318. if (currentFace !== undefined) {
  80319. // Loading a single face
  80320. break;
  80321. }
  80322. }
  80323. };
  80324. DDSTools.StoreLODInAlphaChannel = false;
  80325. return DDSTools;
  80326. }());
  80327. BABYLON.DDSTools = DDSTools;
  80328. })(BABYLON || (BABYLON = {}));
  80329. //# sourceMappingURL=babylon.dds.js.map
  80330. "use strict";
  80331. var BABYLON;
  80332. (function (BABYLON) {
  80333. /**
  80334. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80335. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80336. */
  80337. var KhronosTextureContainer = /** @class */ (function () {
  80338. /**
  80339. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80340. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80341. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80342. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80343. */
  80344. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80345. this.arrayBuffer = arrayBuffer;
  80346. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80347. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80348. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80349. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80350. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80351. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80352. BABYLON.Tools.Error("texture missing KTX identifier");
  80353. return;
  80354. }
  80355. // load the reset of the header in native 32 bit int
  80356. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80357. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80358. var oppositeEndianess = header[0] === 0x01020304;
  80359. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80360. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80361. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80362. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80363. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80364. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80365. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80366. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80367. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80368. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80369. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80370. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80371. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80372. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80373. if (this.glType !== 0) {
  80374. BABYLON.Tools.Error("only compressed formats currently supported");
  80375. return;
  80376. }
  80377. else {
  80378. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80379. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80380. }
  80381. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80382. BABYLON.Tools.Error("only 2D textures currently supported");
  80383. return;
  80384. }
  80385. if (this.numberOfArrayElements !== 0) {
  80386. BABYLON.Tools.Error("texture arrays not currently supported");
  80387. return;
  80388. }
  80389. if (this.numberOfFaces !== facesExpected) {
  80390. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80391. return;
  80392. }
  80393. // we now have a completely validated file, so could use existence of loadType as success
  80394. // would need to make this more elaborate & adjust checks above to support more than one load type
  80395. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80396. }
  80397. // not as fast hardware based, but will probably never need to use
  80398. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80399. return ((val & 0xFF) << 24)
  80400. | ((val & 0xFF00) << 8)
  80401. | ((val >> 8) & 0xFF00)
  80402. | ((val >> 24) & 0xFF);
  80403. };
  80404. /**
  80405. * It is assumed that the texture has already been created & is currently bound
  80406. */
  80407. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80408. switch (this.loadType) {
  80409. case KhronosTextureContainer.COMPRESSED_2D:
  80410. this._upload2DCompressedLevels(gl, loadMipmaps);
  80411. break;
  80412. case KhronosTextureContainer.TEX_2D:
  80413. case KhronosTextureContainer.COMPRESSED_3D:
  80414. case KhronosTextureContainer.TEX_3D:
  80415. }
  80416. };
  80417. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80418. // initialize width & height for level 1
  80419. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80420. var width = this.pixelWidth;
  80421. var height = this.pixelHeight;
  80422. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80423. for (var level = 0; level < mipmapCount; level++) {
  80424. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80425. for (var face = 0; face < this.numberOfFaces; face++) {
  80426. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80427. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80428. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80429. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80430. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80431. }
  80432. width = Math.max(1.0, width * 0.5);
  80433. height = Math.max(1.0, height * 0.5);
  80434. }
  80435. };
  80436. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80437. // load types
  80438. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80439. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80440. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80441. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80442. return KhronosTextureContainer;
  80443. }());
  80444. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80445. })(BABYLON || (BABYLON = {}));
  80446. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80447. "use strict";
  80448. var BABYLON;
  80449. (function (BABYLON) {
  80450. var Debug = /** @class */ (function () {
  80451. function Debug() {
  80452. }
  80453. Debug.AxesViewer = /** @class */ (function () {
  80454. function AxesViewer(scene, scaleLines) {
  80455. if (scaleLines === void 0) { scaleLines = 1; }
  80456. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80457. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80458. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80459. this.scaleLines = 1;
  80460. this.scaleLines = scaleLines;
  80461. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80462. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80463. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80464. this._xmesh.renderingGroupId = 2;
  80465. this._ymesh.renderingGroupId = 2;
  80466. this._zmesh.renderingGroupId = 2;
  80467. this._xmesh.material.checkReadyOnlyOnce = true;
  80468. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80469. this._ymesh.material.checkReadyOnlyOnce = true;
  80470. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80471. this._zmesh.material.checkReadyOnlyOnce = true;
  80472. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80473. this.scene = scene;
  80474. }
  80475. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80476. var scaleLines = this.scaleLines;
  80477. if (this._xmesh) {
  80478. this._xmesh.position.copyFrom(position);
  80479. }
  80480. if (this._ymesh) {
  80481. this._ymesh.position.copyFrom(position);
  80482. }
  80483. if (this._zmesh) {
  80484. this._zmesh.position.copyFrom(position);
  80485. }
  80486. var point2 = this._xline[1];
  80487. point2.x = xaxis.x * scaleLines;
  80488. point2.y = xaxis.y * scaleLines;
  80489. point2.z = xaxis.z * scaleLines;
  80490. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80491. point2 = this._yline[1];
  80492. point2.x = yaxis.x * scaleLines;
  80493. point2.y = yaxis.y * scaleLines;
  80494. point2.z = yaxis.z * scaleLines;
  80495. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80496. point2 = this._zline[1];
  80497. point2.x = zaxis.x * scaleLines;
  80498. point2.y = zaxis.y * scaleLines;
  80499. point2.z = zaxis.z * scaleLines;
  80500. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80501. };
  80502. AxesViewer.prototype.dispose = function () {
  80503. if (this._xmesh) {
  80504. this._xmesh.dispose();
  80505. }
  80506. if (this._ymesh) {
  80507. this._ymesh.dispose();
  80508. }
  80509. if (this._zmesh) {
  80510. this._zmesh.dispose();
  80511. }
  80512. this._xmesh = null;
  80513. this._ymesh = null;
  80514. this._zmesh = null;
  80515. this.scene = null;
  80516. };
  80517. return AxesViewer;
  80518. }());
  80519. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80520. __extends(BoneAxesViewer, _super);
  80521. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80522. if (scaleLines === void 0) { scaleLines = 1; }
  80523. var _this = _super.call(this, scene, scaleLines) || this;
  80524. _this.pos = BABYLON.Vector3.Zero();
  80525. _this.xaxis = BABYLON.Vector3.Zero();
  80526. _this.yaxis = BABYLON.Vector3.Zero();
  80527. _this.zaxis = BABYLON.Vector3.Zero();
  80528. _this.mesh = mesh;
  80529. _this.bone = bone;
  80530. return _this;
  80531. }
  80532. BoneAxesViewer.prototype.update = function () {
  80533. if (!this.mesh || !this.bone) {
  80534. return;
  80535. }
  80536. var bone = this.bone;
  80537. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80538. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80539. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80540. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80541. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80542. };
  80543. BoneAxesViewer.prototype.dispose = function () {
  80544. if (this.mesh) {
  80545. this.mesh = null;
  80546. this.bone = null;
  80547. _super.prototype.dispose.call(this);
  80548. }
  80549. };
  80550. return BoneAxesViewer;
  80551. }(Debug.AxesViewer));
  80552. Debug.PhysicsViewer = /** @class */ (function () {
  80553. function PhysicsViewer(scene) {
  80554. this._impostors = [];
  80555. this._meshes = [];
  80556. this._numMeshes = 0;
  80557. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80558. var physicEngine = this._scene.getPhysicsEngine();
  80559. if (physicEngine) {
  80560. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80561. }
  80562. }
  80563. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80564. var plugin = this._physicsEnginePlugin;
  80565. for (var i = 0; i < this._numMeshes; i++) {
  80566. var impostor = this._impostors[i];
  80567. if (!impostor) {
  80568. continue;
  80569. }
  80570. if (impostor.isDisposed) {
  80571. this.hideImpostor(this._impostors[i--]);
  80572. }
  80573. else {
  80574. var mesh = this._meshes[i];
  80575. if (mesh && plugin) {
  80576. plugin.syncMeshWithImpostor(mesh, impostor);
  80577. }
  80578. }
  80579. }
  80580. };
  80581. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80582. if (!this._scene) {
  80583. return;
  80584. }
  80585. for (var i = 0; i < this._numMeshes; i++) {
  80586. if (this._impostors[i] == impostor) {
  80587. return;
  80588. }
  80589. }
  80590. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80591. if (debugMesh) {
  80592. this._impostors[this._numMeshes] = impostor;
  80593. this._meshes[this._numMeshes] = debugMesh;
  80594. if (this._numMeshes === 0) {
  80595. this._renderFunction = this._updateDebugMeshes.bind(this);
  80596. this._scene.registerBeforeRender(this._renderFunction);
  80597. }
  80598. this._numMeshes++;
  80599. }
  80600. };
  80601. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80602. if (!impostor || !this._scene) {
  80603. return;
  80604. }
  80605. var removed = false;
  80606. for (var i = 0; i < this._numMeshes; i++) {
  80607. if (this._impostors[i] == impostor) {
  80608. var mesh = this._meshes[i];
  80609. if (!mesh) {
  80610. continue;
  80611. }
  80612. this._scene.removeMesh(mesh);
  80613. mesh.dispose();
  80614. this._numMeshes--;
  80615. if (this._numMeshes > 0) {
  80616. this._meshes[i] = this._meshes[this._numMeshes];
  80617. this._impostors[i] = this._impostors[this._numMeshes];
  80618. this._meshes[this._numMeshes] = null;
  80619. this._impostors[this._numMeshes] = null;
  80620. }
  80621. else {
  80622. this._meshes[0] = null;
  80623. this._impostors[0] = null;
  80624. }
  80625. removed = true;
  80626. break;
  80627. }
  80628. }
  80629. if (removed && this._numMeshes === 0) {
  80630. this._scene.unregisterBeforeRender(this._renderFunction);
  80631. }
  80632. };
  80633. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80634. if (!this._debugMaterial) {
  80635. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80636. this._debugMaterial.wireframe = true;
  80637. }
  80638. return this._debugMaterial;
  80639. };
  80640. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80641. if (!this._debugBoxMesh) {
  80642. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80643. this._debugBoxMesh.renderingGroupId = 1;
  80644. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80645. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80646. scene.removeMesh(this._debugBoxMesh);
  80647. }
  80648. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80649. };
  80650. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80651. if (!this._debugSphereMesh) {
  80652. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80653. this._debugSphereMesh.renderingGroupId = 1;
  80654. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80655. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80656. scene.removeMesh(this._debugSphereMesh);
  80657. }
  80658. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80659. };
  80660. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80661. var mesh = null;
  80662. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80663. mesh = this._getDebugBoxMesh(scene);
  80664. impostor.getBoxSizeToRef(mesh.scaling);
  80665. }
  80666. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80667. mesh = this._getDebugSphereMesh(scene);
  80668. var radius = impostor.getRadius();
  80669. mesh.scaling.x = radius * 2;
  80670. mesh.scaling.y = radius * 2;
  80671. mesh.scaling.z = radius * 2;
  80672. }
  80673. return mesh;
  80674. };
  80675. PhysicsViewer.prototype.dispose = function () {
  80676. for (var i = 0; i < this._numMeshes; i++) {
  80677. this.hideImpostor(this._impostors[i]);
  80678. }
  80679. if (this._debugBoxMesh) {
  80680. this._debugBoxMesh.dispose();
  80681. }
  80682. if (this._debugSphereMesh) {
  80683. this._debugSphereMesh.dispose();
  80684. }
  80685. if (this._debugMaterial) {
  80686. this._debugMaterial.dispose();
  80687. }
  80688. this._impostors.length = 0;
  80689. this._scene = null;
  80690. this._physicsEnginePlugin = null;
  80691. };
  80692. return PhysicsViewer;
  80693. }());
  80694. Debug.SkeletonViewer = /** @class */ (function () {
  80695. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80696. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80697. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80698. this.skeleton = skeleton;
  80699. this.mesh = mesh;
  80700. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80701. this.renderingGroupId = renderingGroupId;
  80702. this.color = BABYLON.Color3.White();
  80703. this._debugLines = new Array();
  80704. this._isEnabled = false;
  80705. this._scene = scene;
  80706. this.update();
  80707. this._renderFunction = this.update.bind(this);
  80708. }
  80709. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80710. get: function () {
  80711. return this._isEnabled;
  80712. },
  80713. set: function (value) {
  80714. if (this._isEnabled === value) {
  80715. return;
  80716. }
  80717. this._isEnabled = value;
  80718. if (value) {
  80719. this._scene.registerBeforeRender(this._renderFunction);
  80720. }
  80721. else {
  80722. this._scene.unregisterBeforeRender(this._renderFunction);
  80723. }
  80724. },
  80725. enumerable: true,
  80726. configurable: true
  80727. });
  80728. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80729. if (x === void 0) { x = 0; }
  80730. if (y === void 0) { y = 0; }
  80731. if (z === void 0) { z = 0; }
  80732. var tmat = BABYLON.Tmp.Matrix[0];
  80733. var parentBone = bone.getParent();
  80734. tmat.copyFrom(bone.getLocalMatrix());
  80735. if (x !== 0 || y !== 0 || z !== 0) {
  80736. var tmat2 = BABYLON.Tmp.Matrix[1];
  80737. BABYLON.Matrix.IdentityToRef(tmat2);
  80738. tmat2.m[12] = x;
  80739. tmat2.m[13] = y;
  80740. tmat2.m[14] = z;
  80741. tmat2.multiplyToRef(tmat, tmat);
  80742. }
  80743. if (parentBone) {
  80744. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80745. }
  80746. tmat.multiplyToRef(meshMat, tmat);
  80747. position.x = tmat.m[12];
  80748. position.y = tmat.m[13];
  80749. position.z = tmat.m[14];
  80750. };
  80751. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80752. var len = bones.length;
  80753. var meshPos = this.mesh.position;
  80754. for (var i = 0; i < len; i++) {
  80755. var bone = bones[i];
  80756. var points = this._debugLines[i];
  80757. if (!points) {
  80758. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80759. this._debugLines[i] = points;
  80760. }
  80761. this._getBonePosition(points[0], bone, meshMat);
  80762. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80763. points[0].subtractInPlace(meshPos);
  80764. points[1].subtractInPlace(meshPos);
  80765. }
  80766. };
  80767. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80768. var len = bones.length;
  80769. var boneNum = 0;
  80770. var meshPos = this.mesh.position;
  80771. for (var i = len - 1; i >= 0; i--) {
  80772. var childBone = bones[i];
  80773. var parentBone = childBone.getParent();
  80774. if (!parentBone) {
  80775. continue;
  80776. }
  80777. var points = this._debugLines[boneNum];
  80778. if (!points) {
  80779. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80780. this._debugLines[boneNum] = points;
  80781. }
  80782. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80783. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80784. points[0].subtractInPlace(meshPos);
  80785. points[1].subtractInPlace(meshPos);
  80786. boneNum++;
  80787. }
  80788. };
  80789. SkeletonViewer.prototype.update = function () {
  80790. if (this.autoUpdateBonesMatrices) {
  80791. this.skeleton.computeAbsoluteTransforms();
  80792. }
  80793. if (this.skeleton.bones[0].length === undefined) {
  80794. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80795. }
  80796. else {
  80797. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80798. }
  80799. if (!this._debugMesh) {
  80800. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80801. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80802. }
  80803. else {
  80804. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80805. }
  80806. this._debugMesh.position.copyFrom(this.mesh.position);
  80807. this._debugMesh.color = this.color;
  80808. };
  80809. SkeletonViewer.prototype.dispose = function () {
  80810. if (this._debugMesh) {
  80811. this.isEnabled = false;
  80812. this._debugMesh.dispose();
  80813. this._debugMesh = null;
  80814. }
  80815. };
  80816. return SkeletonViewer;
  80817. }());
  80818. return Debug;
  80819. }());
  80820. BABYLON.Debug = Debug;
  80821. })(BABYLON || (BABYLON = {}));
  80822. //# sourceMappingURL=babylon.debugModules.js.map
  80823. "use strict";
  80824. var BABYLON;
  80825. (function (BABYLON) {
  80826. var RayHelper = /** @class */ (function () {
  80827. function RayHelper(ray) {
  80828. this.ray = ray;
  80829. }
  80830. RayHelper.CreateAndShow = function (ray, scene, color) {
  80831. var helper = new RayHelper(ray);
  80832. helper.show(scene, color);
  80833. return helper;
  80834. };
  80835. RayHelper.prototype.show = function (scene, color) {
  80836. if (!this._renderFunction && this.ray) {
  80837. var ray = this.ray;
  80838. this._renderFunction = this._render.bind(this);
  80839. this._scene = scene;
  80840. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80841. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80842. if (this._renderFunction) {
  80843. this._scene.registerBeforeRender(this._renderFunction);
  80844. }
  80845. }
  80846. if (color && this._renderLine) {
  80847. this._renderLine.color.copyFrom(color);
  80848. }
  80849. };
  80850. RayHelper.prototype.hide = function () {
  80851. if (this._renderFunction && this._scene) {
  80852. this._scene.unregisterBeforeRender(this._renderFunction);
  80853. this._scene = null;
  80854. this._renderFunction = null;
  80855. if (this._renderLine) {
  80856. this._renderLine.dispose();
  80857. this._renderLine = null;
  80858. }
  80859. this._renderPoints = [];
  80860. }
  80861. };
  80862. RayHelper.prototype._render = function () {
  80863. var ray = this.ray;
  80864. if (!ray) {
  80865. return;
  80866. }
  80867. var point = this._renderPoints[1];
  80868. var len = Math.min(ray.length, 1000000);
  80869. point.copyFrom(ray.direction);
  80870. point.scaleInPlace(len);
  80871. point.addInPlace(ray.origin);
  80872. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80873. };
  80874. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80875. this._attachedToMesh = mesh;
  80876. var ray = this.ray;
  80877. if (!ray) {
  80878. return;
  80879. }
  80880. if (!ray.direction) {
  80881. ray.direction = BABYLON.Vector3.Zero();
  80882. }
  80883. if (!ray.origin) {
  80884. ray.origin = BABYLON.Vector3.Zero();
  80885. }
  80886. if (length) {
  80887. ray.length = length;
  80888. }
  80889. if (!meshSpaceOrigin) {
  80890. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80891. }
  80892. if (!meshSpaceDirection) {
  80893. // -1 so that this will work with Mesh.lookAt
  80894. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80895. }
  80896. if (!this._meshSpaceDirection) {
  80897. this._meshSpaceDirection = meshSpaceDirection.clone();
  80898. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80899. }
  80900. else {
  80901. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80902. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80903. }
  80904. if (!this._updateToMeshFunction) {
  80905. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80906. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80907. }
  80908. this._updateToMesh();
  80909. };
  80910. RayHelper.prototype.detachFromMesh = function () {
  80911. if (this._attachedToMesh) {
  80912. if (this._updateToMeshFunction) {
  80913. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80914. }
  80915. this._attachedToMesh = null;
  80916. this._updateToMeshFunction = null;
  80917. }
  80918. };
  80919. RayHelper.prototype._updateToMesh = function () {
  80920. var ray = this.ray;
  80921. if (!this._attachedToMesh || !ray) {
  80922. return;
  80923. }
  80924. if (this._attachedToMesh._isDisposed) {
  80925. this.detachFromMesh();
  80926. return;
  80927. }
  80928. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80929. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80930. };
  80931. RayHelper.prototype.dispose = function () {
  80932. this.hide();
  80933. this.detachFromMesh();
  80934. this.ray = null;
  80935. };
  80936. return RayHelper;
  80937. }());
  80938. BABYLON.RayHelper = RayHelper;
  80939. })(BABYLON || (BABYLON = {}));
  80940. //# sourceMappingURL=babylon.rayHelper.js.map
  80941. "use strict";
  80942. var BABYLON;
  80943. (function (BABYLON) {
  80944. // load the inspector using require, if not present in the global namespace.
  80945. var DebugLayer = /** @class */ (function () {
  80946. function DebugLayer(scene) {
  80947. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80948. this._scene = scene;
  80949. // load inspector using require, if it doesn't exist on the global namespace.
  80950. }
  80951. /** Creates the inspector window. */
  80952. DebugLayer.prototype._createInspector = function (config) {
  80953. if (config === void 0) { config = {}; }
  80954. var popup = config.popup || false;
  80955. var initialTab = config.initialTab || 0;
  80956. var parentElement = config.parentElement || null;
  80957. if (!this._inspector) {
  80958. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80959. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80960. } // else nothing to do,; instance is already existing
  80961. };
  80962. DebugLayer.prototype.isVisible = function () {
  80963. if (!this._inspector) {
  80964. return false;
  80965. }
  80966. return true;
  80967. };
  80968. DebugLayer.prototype.hide = function () {
  80969. if (this._inspector) {
  80970. try {
  80971. this._inspector.dispose();
  80972. }
  80973. catch (e) {
  80974. // If the inspector has been removed directly from the inspector tool
  80975. }
  80976. this._inspector = null;
  80977. }
  80978. };
  80979. DebugLayer.prototype.show = function (config) {
  80980. if (config === void 0) { config = {}; }
  80981. if (typeof this.BJSINSPECTOR == 'undefined') {
  80982. // Load inspector and add it to the DOM
  80983. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80984. }
  80985. else {
  80986. // Otherwise creates the inspector
  80987. this._createInspector(config);
  80988. }
  80989. };
  80990. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80991. return DebugLayer;
  80992. }());
  80993. BABYLON.DebugLayer = DebugLayer;
  80994. })(BABYLON || (BABYLON = {}));
  80995. //# sourceMappingURL=babylon.debugLayer.js.map
  80996. "use strict";
  80997. var BABYLON;
  80998. (function (BABYLON) {
  80999. var BoundingBoxRenderer = /** @class */ (function () {
  81000. function BoundingBoxRenderer(scene) {
  81001. this.frontColor = new BABYLON.Color3(1, 1, 1);
  81002. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  81003. this.showBackLines = true;
  81004. this.renderList = new BABYLON.SmartArray(32);
  81005. this._vertexBuffers = {};
  81006. this._scene = scene;
  81007. }
  81008. BoundingBoxRenderer.prototype._prepareRessources = function () {
  81009. if (this._colorShader) {
  81010. return;
  81011. }
  81012. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  81013. attributes: [BABYLON.VertexBuffer.PositionKind],
  81014. uniforms: ["world", "viewProjection", "color"]
  81015. });
  81016. var engine = this._scene.getEngine();
  81017. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  81018. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  81019. this._createIndexBuffer();
  81020. };
  81021. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  81022. var engine = this._scene.getEngine();
  81023. 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]);
  81024. };
  81025. BoundingBoxRenderer.prototype._rebuild = function () {
  81026. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81027. if (vb) {
  81028. vb._rebuild();
  81029. }
  81030. this._createIndexBuffer();
  81031. };
  81032. BoundingBoxRenderer.prototype.reset = function () {
  81033. this.renderList.reset();
  81034. };
  81035. BoundingBoxRenderer.prototype.render = function () {
  81036. if (this.renderList.length === 0) {
  81037. return;
  81038. }
  81039. this._prepareRessources();
  81040. if (!this._colorShader.isReady()) {
  81041. return;
  81042. }
  81043. var engine = this._scene.getEngine();
  81044. engine.setDepthWrite(false);
  81045. this._colorShader._preBind();
  81046. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  81047. var boundingBox = this.renderList.data[boundingBoxIndex];
  81048. var min = boundingBox.minimum;
  81049. var max = boundingBox.maximum;
  81050. var diff = max.subtract(min);
  81051. var median = min.add(diff.scale(0.5));
  81052. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81053. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81054. .multiply(boundingBox.getWorldMatrix());
  81055. // VBOs
  81056. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81057. if (this.showBackLines) {
  81058. // Back
  81059. engine.setDepthFunctionToGreaterOrEqual();
  81060. this._scene.resetCachedMaterial();
  81061. this._colorShader.setColor4("color", this.backColor.toColor4());
  81062. this._colorShader.bind(worldMatrix);
  81063. // Draw order
  81064. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81065. }
  81066. // Front
  81067. engine.setDepthFunctionToLess();
  81068. this._scene.resetCachedMaterial();
  81069. this._colorShader.setColor4("color", this.frontColor.toColor4());
  81070. this._colorShader.bind(worldMatrix);
  81071. // Draw order
  81072. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81073. }
  81074. this._colorShader.unbind();
  81075. engine.setDepthFunctionToLessOrEqual();
  81076. engine.setDepthWrite(true);
  81077. };
  81078. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  81079. this._prepareRessources();
  81080. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  81081. return;
  81082. }
  81083. var engine = this._scene.getEngine();
  81084. engine.setDepthWrite(false);
  81085. engine.setColorWrite(false);
  81086. this._colorShader._preBind();
  81087. var boundingBox = mesh._boundingInfo.boundingBox;
  81088. var min = boundingBox.minimum;
  81089. var max = boundingBox.maximum;
  81090. var diff = max.subtract(min);
  81091. var median = min.add(diff.scale(0.5));
  81092. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81093. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81094. .multiply(boundingBox.getWorldMatrix());
  81095. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81096. engine.setDepthFunctionToLess();
  81097. this._scene.resetCachedMaterial();
  81098. this._colorShader.bind(worldMatrix);
  81099. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81100. this._colorShader.unbind();
  81101. engine.setDepthFunctionToLessOrEqual();
  81102. engine.setDepthWrite(true);
  81103. engine.setColorWrite(true);
  81104. };
  81105. BoundingBoxRenderer.prototype.dispose = function () {
  81106. if (!this._colorShader) {
  81107. return;
  81108. }
  81109. this.renderList.dispose();
  81110. this._colorShader.dispose();
  81111. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81112. if (buffer) {
  81113. buffer.dispose();
  81114. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81115. }
  81116. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81117. };
  81118. return BoundingBoxRenderer;
  81119. }());
  81120. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  81121. })(BABYLON || (BABYLON = {}));
  81122. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  81123. "use strict";
  81124. var BABYLON;
  81125. (function (BABYLON) {
  81126. var MorphTarget = /** @class */ (function () {
  81127. function MorphTarget(name, influence) {
  81128. if (influence === void 0) { influence = 0; }
  81129. this.name = name;
  81130. this.animations = new Array();
  81131. this._positions = null;
  81132. this._normals = null;
  81133. this._tangents = null;
  81134. this.onInfluenceChanged = new BABYLON.Observable();
  81135. this.influence = influence;
  81136. }
  81137. Object.defineProperty(MorphTarget.prototype, "influence", {
  81138. get: function () {
  81139. return this._influence;
  81140. },
  81141. set: function (influence) {
  81142. if (this._influence === influence) {
  81143. return;
  81144. }
  81145. var previous = this._influence;
  81146. this._influence = influence;
  81147. if (this.onInfluenceChanged.hasObservers) {
  81148. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  81149. }
  81150. },
  81151. enumerable: true,
  81152. configurable: true
  81153. });
  81154. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  81155. get: function () {
  81156. return !!this._positions;
  81157. },
  81158. enumerable: true,
  81159. configurable: true
  81160. });
  81161. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  81162. get: function () {
  81163. return !!this._normals;
  81164. },
  81165. enumerable: true,
  81166. configurable: true
  81167. });
  81168. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  81169. get: function () {
  81170. return !!this._tangents;
  81171. },
  81172. enumerable: true,
  81173. configurable: true
  81174. });
  81175. MorphTarget.prototype.setPositions = function (data) {
  81176. this._positions = data;
  81177. };
  81178. MorphTarget.prototype.getPositions = function () {
  81179. return this._positions;
  81180. };
  81181. MorphTarget.prototype.setNormals = function (data) {
  81182. this._normals = data;
  81183. };
  81184. MorphTarget.prototype.getNormals = function () {
  81185. return this._normals;
  81186. };
  81187. MorphTarget.prototype.setTangents = function (data) {
  81188. this._tangents = data;
  81189. };
  81190. MorphTarget.prototype.getTangents = function () {
  81191. return this._tangents;
  81192. };
  81193. /**
  81194. * Serializes the current target into a Serialization object.
  81195. * Returns the serialized object.
  81196. */
  81197. MorphTarget.prototype.serialize = function () {
  81198. var serializationObject = {};
  81199. serializationObject.name = this.name;
  81200. serializationObject.influence = this.influence;
  81201. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  81202. if (this.hasNormals) {
  81203. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  81204. }
  81205. if (this.hasTangents) {
  81206. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  81207. }
  81208. // Animations
  81209. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  81210. return serializationObject;
  81211. };
  81212. // Statics
  81213. MorphTarget.Parse = function (serializationObject) {
  81214. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  81215. result.setPositions(serializationObject.positions);
  81216. if (serializationObject.normals) {
  81217. result.setNormals(serializationObject.normals);
  81218. }
  81219. if (serializationObject.tangents) {
  81220. result.setTangents(serializationObject.tangents);
  81221. }
  81222. // Animations
  81223. if (serializationObject.animations) {
  81224. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  81225. var parsedAnimation = serializationObject.animations[animationIndex];
  81226. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  81227. }
  81228. }
  81229. return result;
  81230. };
  81231. MorphTarget.FromMesh = function (mesh, name, influence) {
  81232. if (!name) {
  81233. name = mesh.name;
  81234. }
  81235. var result = new MorphTarget(name, influence);
  81236. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81237. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  81238. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  81239. }
  81240. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  81241. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  81242. }
  81243. return result;
  81244. };
  81245. return MorphTarget;
  81246. }());
  81247. BABYLON.MorphTarget = MorphTarget;
  81248. })(BABYLON || (BABYLON = {}));
  81249. //# sourceMappingURL=babylon.morphTarget.js.map
  81250. "use strict";
  81251. var BABYLON;
  81252. (function (BABYLON) {
  81253. var MorphTargetManager = /** @class */ (function () {
  81254. function MorphTargetManager(scene) {
  81255. if (scene === void 0) { scene = null; }
  81256. this._targets = new Array();
  81257. this._targetObservable = new Array();
  81258. this._activeTargets = new BABYLON.SmartArray(16);
  81259. this._supportsNormals = false;
  81260. this._supportsTangents = false;
  81261. this._vertexCount = 0;
  81262. this._uniqueId = 0;
  81263. this._tempInfluences = new Array();
  81264. if (!scene) {
  81265. scene = BABYLON.Engine.LastCreatedScene;
  81266. }
  81267. this._scene = scene;
  81268. if (this._scene) {
  81269. this._scene.morphTargetManagers.push(this);
  81270. this._uniqueId = this._scene.getUniqueId();
  81271. }
  81272. }
  81273. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  81274. get: function () {
  81275. return this._uniqueId;
  81276. },
  81277. enumerable: true,
  81278. configurable: true
  81279. });
  81280. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  81281. get: function () {
  81282. return this._vertexCount;
  81283. },
  81284. enumerable: true,
  81285. configurable: true
  81286. });
  81287. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  81288. get: function () {
  81289. return this._supportsNormals;
  81290. },
  81291. enumerable: true,
  81292. configurable: true
  81293. });
  81294. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  81295. get: function () {
  81296. return this._supportsTangents;
  81297. },
  81298. enumerable: true,
  81299. configurable: true
  81300. });
  81301. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  81302. get: function () {
  81303. return this._targets.length;
  81304. },
  81305. enumerable: true,
  81306. configurable: true
  81307. });
  81308. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  81309. get: function () {
  81310. return this._activeTargets.length;
  81311. },
  81312. enumerable: true,
  81313. configurable: true
  81314. });
  81315. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81316. get: function () {
  81317. return this._influences;
  81318. },
  81319. enumerable: true,
  81320. configurable: true
  81321. });
  81322. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81323. return this._activeTargets.data[index];
  81324. };
  81325. MorphTargetManager.prototype.getTarget = function (index) {
  81326. return this._targets[index];
  81327. };
  81328. MorphTargetManager.prototype.addTarget = function (target) {
  81329. var _this = this;
  81330. this._targets.push(target);
  81331. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81332. _this._syncActiveTargets(needUpdate);
  81333. }));
  81334. this._syncActiveTargets(true);
  81335. };
  81336. MorphTargetManager.prototype.removeTarget = function (target) {
  81337. var index = this._targets.indexOf(target);
  81338. if (index >= 0) {
  81339. this._targets.splice(index, 1);
  81340. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81341. this._syncActiveTargets(true);
  81342. }
  81343. };
  81344. /**
  81345. * Serializes the current manager into a Serialization object.
  81346. * Returns the serialized object.
  81347. */
  81348. MorphTargetManager.prototype.serialize = function () {
  81349. var serializationObject = {};
  81350. serializationObject.id = this.uniqueId;
  81351. serializationObject.targets = [];
  81352. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81353. var target = _a[_i];
  81354. serializationObject.targets.push(target.serialize());
  81355. }
  81356. return serializationObject;
  81357. };
  81358. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81359. var influenceCount = 0;
  81360. this._activeTargets.reset();
  81361. this._supportsNormals = true;
  81362. this._supportsTangents = true;
  81363. this._vertexCount = 0;
  81364. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81365. var target = _a[_i];
  81366. this._activeTargets.push(target);
  81367. this._tempInfluences[influenceCount++] = target.influence;
  81368. var positions = target.getPositions();
  81369. if (positions) {
  81370. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81371. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81372. var vertexCount = positions.length / 3;
  81373. if (this._vertexCount === 0) {
  81374. this._vertexCount = vertexCount;
  81375. }
  81376. else if (this._vertexCount !== vertexCount) {
  81377. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81378. return;
  81379. }
  81380. }
  81381. }
  81382. if (!this._influences || this._influences.length !== influenceCount) {
  81383. this._influences = new Float32Array(influenceCount);
  81384. }
  81385. for (var index = 0; index < influenceCount; index++) {
  81386. this._influences[index] = this._tempInfluences[index];
  81387. }
  81388. if (needUpdate && this._scene) {
  81389. // Flag meshes as dirty to resync with the active targets
  81390. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81391. var mesh = _c[_b];
  81392. if (mesh.morphTargetManager === this) {
  81393. mesh._syncGeometryWithMorphTargetManager();
  81394. }
  81395. }
  81396. }
  81397. };
  81398. // Statics
  81399. MorphTargetManager.Parse = function (serializationObject, scene) {
  81400. var result = new MorphTargetManager(scene);
  81401. result._uniqueId = serializationObject.id;
  81402. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81403. var targetData = _a[_i];
  81404. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81405. }
  81406. return result;
  81407. };
  81408. return MorphTargetManager;
  81409. }());
  81410. BABYLON.MorphTargetManager = MorphTargetManager;
  81411. })(BABYLON || (BABYLON = {}));
  81412. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81413. "use strict";
  81414. var BABYLON;
  81415. (function (BABYLON) {
  81416. var Octree = /** @class */ (function () {
  81417. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81418. if (maxDepth === void 0) { maxDepth = 2; }
  81419. this.maxDepth = maxDepth;
  81420. this.dynamicContent = new Array();
  81421. this._maxBlockCapacity = maxBlockCapacity || 64;
  81422. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81423. this._creationFunc = creationFunc;
  81424. }
  81425. // Methods
  81426. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81427. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81428. };
  81429. Octree.prototype.addMesh = function (entry) {
  81430. for (var index = 0; index < this.blocks.length; index++) {
  81431. var block = this.blocks[index];
  81432. block.addEntry(entry);
  81433. }
  81434. };
  81435. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81436. this._selectionContent.reset();
  81437. for (var index = 0; index < this.blocks.length; index++) {
  81438. var block = this.blocks[index];
  81439. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81440. }
  81441. if (allowDuplicate) {
  81442. this._selectionContent.concat(this.dynamicContent);
  81443. }
  81444. else {
  81445. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81446. }
  81447. return this._selectionContent;
  81448. };
  81449. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81450. this._selectionContent.reset();
  81451. for (var index = 0; index < this.blocks.length; index++) {
  81452. var block = this.blocks[index];
  81453. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81454. }
  81455. if (allowDuplicate) {
  81456. this._selectionContent.concat(this.dynamicContent);
  81457. }
  81458. else {
  81459. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81460. }
  81461. return this._selectionContent;
  81462. };
  81463. Octree.prototype.intersectsRay = function (ray) {
  81464. this._selectionContent.reset();
  81465. for (var index = 0; index < this.blocks.length; index++) {
  81466. var block = this.blocks[index];
  81467. block.intersectsRay(ray, this._selectionContent);
  81468. }
  81469. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81470. return this._selectionContent;
  81471. };
  81472. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81473. target.blocks = new Array();
  81474. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81475. // Segmenting space
  81476. for (var x = 0; x < 2; x++) {
  81477. for (var y = 0; y < 2; y++) {
  81478. for (var z = 0; z < 2; z++) {
  81479. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81480. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81481. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81482. block.addEntries(entries);
  81483. target.blocks.push(block);
  81484. }
  81485. }
  81486. }
  81487. };
  81488. Octree.CreationFuncForMeshes = function (entry, block) {
  81489. var boundingInfo = entry.getBoundingInfo();
  81490. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81491. block.entries.push(entry);
  81492. }
  81493. };
  81494. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81495. var boundingInfo = entry.getBoundingInfo();
  81496. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81497. block.entries.push(entry);
  81498. }
  81499. };
  81500. return Octree;
  81501. }());
  81502. BABYLON.Octree = Octree;
  81503. })(BABYLON || (BABYLON = {}));
  81504. //# sourceMappingURL=babylon.octree.js.map
  81505. "use strict";
  81506. var BABYLON;
  81507. (function (BABYLON) {
  81508. var OctreeBlock = /** @class */ (function () {
  81509. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81510. this.entries = new Array();
  81511. this._boundingVectors = new Array();
  81512. this._capacity = capacity;
  81513. this._depth = depth;
  81514. this._maxDepth = maxDepth;
  81515. this._creationFunc = creationFunc;
  81516. this._minPoint = minPoint;
  81517. this._maxPoint = maxPoint;
  81518. this._boundingVectors.push(minPoint.clone());
  81519. this._boundingVectors.push(maxPoint.clone());
  81520. this._boundingVectors.push(minPoint.clone());
  81521. this._boundingVectors[2].x = maxPoint.x;
  81522. this._boundingVectors.push(minPoint.clone());
  81523. this._boundingVectors[3].y = maxPoint.y;
  81524. this._boundingVectors.push(minPoint.clone());
  81525. this._boundingVectors[4].z = maxPoint.z;
  81526. this._boundingVectors.push(maxPoint.clone());
  81527. this._boundingVectors[5].z = minPoint.z;
  81528. this._boundingVectors.push(maxPoint.clone());
  81529. this._boundingVectors[6].x = minPoint.x;
  81530. this._boundingVectors.push(maxPoint.clone());
  81531. this._boundingVectors[7].y = minPoint.y;
  81532. }
  81533. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81534. // Property
  81535. get: function () {
  81536. return this._capacity;
  81537. },
  81538. enumerable: true,
  81539. configurable: true
  81540. });
  81541. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81542. get: function () {
  81543. return this._minPoint;
  81544. },
  81545. enumerable: true,
  81546. configurable: true
  81547. });
  81548. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81549. get: function () {
  81550. return this._maxPoint;
  81551. },
  81552. enumerable: true,
  81553. configurable: true
  81554. });
  81555. // Methods
  81556. OctreeBlock.prototype.addEntry = function (entry) {
  81557. if (this.blocks) {
  81558. for (var index = 0; index < this.blocks.length; index++) {
  81559. var block = this.blocks[index];
  81560. block.addEntry(entry);
  81561. }
  81562. return;
  81563. }
  81564. this._creationFunc(entry, this);
  81565. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81566. this.createInnerBlocks();
  81567. }
  81568. };
  81569. OctreeBlock.prototype.addEntries = function (entries) {
  81570. for (var index = 0; index < entries.length; index++) {
  81571. var mesh = entries[index];
  81572. this.addEntry(mesh);
  81573. }
  81574. };
  81575. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81576. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81577. if (this.blocks) {
  81578. for (var index = 0; index < this.blocks.length; index++) {
  81579. var block = this.blocks[index];
  81580. block.select(frustumPlanes, selection, allowDuplicate);
  81581. }
  81582. return;
  81583. }
  81584. if (allowDuplicate) {
  81585. selection.concat(this.entries);
  81586. }
  81587. else {
  81588. selection.concatWithNoDuplicate(this.entries);
  81589. }
  81590. }
  81591. };
  81592. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81593. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81594. if (this.blocks) {
  81595. for (var index = 0; index < this.blocks.length; index++) {
  81596. var block = this.blocks[index];
  81597. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81598. }
  81599. return;
  81600. }
  81601. if (allowDuplicate) {
  81602. selection.concat(this.entries);
  81603. }
  81604. else {
  81605. selection.concatWithNoDuplicate(this.entries);
  81606. }
  81607. }
  81608. };
  81609. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81610. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81611. if (this.blocks) {
  81612. for (var index = 0; index < this.blocks.length; index++) {
  81613. var block = this.blocks[index];
  81614. block.intersectsRay(ray, selection);
  81615. }
  81616. return;
  81617. }
  81618. selection.concatWithNoDuplicate(this.entries);
  81619. }
  81620. };
  81621. OctreeBlock.prototype.createInnerBlocks = function () {
  81622. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81623. };
  81624. return OctreeBlock;
  81625. }());
  81626. BABYLON.OctreeBlock = OctreeBlock;
  81627. })(BABYLON || (BABYLON = {}));
  81628. //# sourceMappingURL=babylon.octreeBlock.js.map
  81629. "use strict";
  81630. var BABYLON;
  81631. (function (BABYLON) {
  81632. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81633. __extends(VRDistortionCorrectionPostProcess, _super);
  81634. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81635. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81636. 'LensCenter',
  81637. 'Scale',
  81638. 'ScaleIn',
  81639. 'HmdWarpParam'
  81640. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81641. _this._isRightEye = isRightEye;
  81642. _this._distortionFactors = vrMetrics.distortionK;
  81643. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81644. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81645. _this.adaptScaleToCurrentViewport = true;
  81646. _this.onSizeChangedObservable.add(function () {
  81647. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81648. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81649. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81650. });
  81651. _this.onApplyObservable.add(function (effect) {
  81652. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81653. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81654. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81655. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81656. });
  81657. return _this;
  81658. }
  81659. return VRDistortionCorrectionPostProcess;
  81660. }(BABYLON.PostProcess));
  81661. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81662. })(BABYLON || (BABYLON = {}));
  81663. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81664. "use strict";
  81665. var BABYLON;
  81666. (function (BABYLON) {
  81667. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81668. __extends(AnaglyphPostProcess, _super);
  81669. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81670. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81671. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81672. _this.onApplyObservable.add(function (effect) {
  81673. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81674. });
  81675. return _this;
  81676. }
  81677. return AnaglyphPostProcess;
  81678. }(BABYLON.PostProcess));
  81679. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81680. })(BABYLON || (BABYLON = {}));
  81681. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81682. "use strict";
  81683. var BABYLON;
  81684. (function (BABYLON) {
  81685. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81686. __extends(StereoscopicInterlacePostProcess, _super);
  81687. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81688. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81689. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81690. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81691. _this.onSizeChangedObservable.add(function () {
  81692. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81693. });
  81694. _this.onApplyObservable.add(function (effect) {
  81695. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81696. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81697. });
  81698. return _this;
  81699. }
  81700. return StereoscopicInterlacePostProcess;
  81701. }(BABYLON.PostProcess));
  81702. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81703. })(BABYLON || (BABYLON = {}));
  81704. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81705. "use strict";
  81706. var BABYLON;
  81707. (function (BABYLON) {
  81708. /**
  81709. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81710. * Screen rotation is taken into account.
  81711. */
  81712. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81713. function FreeCameraDeviceOrientationInput() {
  81714. var _this = this;
  81715. this._screenOrientationAngle = 0;
  81716. this._screenQuaternion = new BABYLON.Quaternion();
  81717. this._alpha = 0;
  81718. this._beta = 0;
  81719. this._gamma = 0;
  81720. this._orientationChanged = function () {
  81721. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81722. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81723. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81724. };
  81725. this._deviceOrientation = function (evt) {
  81726. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81727. _this._beta = evt.beta !== null ? evt.beta : 0;
  81728. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81729. };
  81730. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81731. this._orientationChanged();
  81732. }
  81733. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81734. get: function () {
  81735. return this._camera;
  81736. },
  81737. set: function (camera) {
  81738. this._camera = camera;
  81739. if (this._camera != null && !this._camera.rotationQuaternion) {
  81740. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81741. }
  81742. },
  81743. enumerable: true,
  81744. configurable: true
  81745. });
  81746. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81747. window.addEventListener("orientationchange", this._orientationChanged);
  81748. window.addEventListener("deviceorientation", this._deviceOrientation);
  81749. //In certain cases, the attach control is called AFTER orientation was changed,
  81750. //So this is needed.
  81751. this._orientationChanged();
  81752. };
  81753. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81754. window.removeEventListener("orientationchange", this._orientationChanged);
  81755. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81756. };
  81757. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81758. //if no device orientation provided, don't update the rotation.
  81759. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81760. if (!this._alpha)
  81761. return;
  81762. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81763. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81764. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81765. //Mirror on XY Plane
  81766. this._camera.rotationQuaternion.z *= -1;
  81767. this._camera.rotationQuaternion.w *= -1;
  81768. };
  81769. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81770. return "FreeCameraDeviceOrientationInput";
  81771. };
  81772. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81773. return "deviceOrientation";
  81774. };
  81775. return FreeCameraDeviceOrientationInput;
  81776. }());
  81777. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81778. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81779. })(BABYLON || (BABYLON = {}));
  81780. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81781. "use strict";
  81782. var BABYLON;
  81783. (function (BABYLON) {
  81784. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81785. function ArcRotateCameraVRDeviceOrientationInput() {
  81786. this.alphaCorrection = 1;
  81787. this.betaCorrection = 1;
  81788. this.gammaCorrection = 1;
  81789. this._alpha = 0;
  81790. this._gamma = 0;
  81791. this._dirty = false;
  81792. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81793. }
  81794. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81795. this.camera.attachControl(element, noPreventDefault);
  81796. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81797. };
  81798. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81799. if (evt.alpha !== null) {
  81800. this._alpha = +evt.alpha | 0;
  81801. }
  81802. if (evt.gamma !== null) {
  81803. this._gamma = +evt.gamma | 0;
  81804. }
  81805. this._dirty = true;
  81806. };
  81807. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81808. if (this._dirty) {
  81809. this._dirty = false;
  81810. if (this._gamma < 0) {
  81811. this._gamma = 180 + this._gamma;
  81812. }
  81813. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81814. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81815. }
  81816. };
  81817. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81818. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81819. };
  81820. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81821. return "ArcRotateCameraVRDeviceOrientationInput";
  81822. };
  81823. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81824. return "VRDeviceOrientation";
  81825. };
  81826. return ArcRotateCameraVRDeviceOrientationInput;
  81827. }());
  81828. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81829. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81830. })(BABYLON || (BABYLON = {}));
  81831. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81832. "use strict";
  81833. var BABYLON;
  81834. (function (BABYLON) {
  81835. var VRCameraMetrics = /** @class */ (function () {
  81836. function VRCameraMetrics() {
  81837. this.compensateDistortion = true;
  81838. }
  81839. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81840. get: function () {
  81841. return this.hResolution / (2 * this.vResolution);
  81842. },
  81843. enumerable: true,
  81844. configurable: true
  81845. });
  81846. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81847. get: function () {
  81848. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81849. },
  81850. enumerable: true,
  81851. configurable: true
  81852. });
  81853. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81854. get: function () {
  81855. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81856. var h = (4 * meters) / this.hScreenSize;
  81857. return BABYLON.Matrix.Translation(h, 0, 0);
  81858. },
  81859. enumerable: true,
  81860. configurable: true
  81861. });
  81862. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81863. get: function () {
  81864. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81865. var h = (4 * meters) / this.hScreenSize;
  81866. return BABYLON.Matrix.Translation(-h, 0, 0);
  81867. },
  81868. enumerable: true,
  81869. configurable: true
  81870. });
  81871. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81872. get: function () {
  81873. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81874. },
  81875. enumerable: true,
  81876. configurable: true
  81877. });
  81878. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81879. get: function () {
  81880. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81881. },
  81882. enumerable: true,
  81883. configurable: true
  81884. });
  81885. VRCameraMetrics.GetDefault = function () {
  81886. var result = new VRCameraMetrics();
  81887. result.hResolution = 1280;
  81888. result.vResolution = 800;
  81889. result.hScreenSize = 0.149759993;
  81890. result.vScreenSize = 0.0935999975;
  81891. result.vScreenCenter = 0.0467999987;
  81892. result.eyeToScreenDistance = 0.0410000011;
  81893. result.lensSeparationDistance = 0.0635000020;
  81894. result.interpupillaryDistance = 0.0640000030;
  81895. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81896. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81897. result.postProcessScaleFactor = 1.714605507808412;
  81898. result.lensCenterOffset = 0.151976421;
  81899. return result;
  81900. };
  81901. return VRCameraMetrics;
  81902. }());
  81903. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81904. })(BABYLON || (BABYLON = {}));
  81905. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81906. "use strict";
  81907. var BABYLON;
  81908. (function (BABYLON) {
  81909. /**
  81910. * This represents a WebVR camera.
  81911. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81912. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81913. */
  81914. var WebVRFreeCamera = /** @class */ (function (_super) {
  81915. __extends(WebVRFreeCamera, _super);
  81916. /**
  81917. * Instantiates a WebVRFreeCamera.
  81918. * @param name The name of the WebVRFreeCamera
  81919. * @param position The starting anchor position for the camera
  81920. * @param scene The scene the camera belongs to
  81921. * @param webVROptions a set of customizable options for the webVRCamera
  81922. */
  81923. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81924. if (webVROptions === void 0) { webVROptions = {}; }
  81925. var _this = _super.call(this, name, position, scene) || this;
  81926. _this.webVROptions = webVROptions;
  81927. /**
  81928. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81929. */
  81930. _this._vrDevice = null;
  81931. /**
  81932. * The rawPose of the vrDevice.
  81933. */
  81934. _this.rawPose = null;
  81935. _this._specsVersion = "1.1";
  81936. _this._attached = false;
  81937. _this._descendants = [];
  81938. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81939. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81940. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81941. _this._standingMatrix = null;
  81942. /**
  81943. * Represents device position in babylon space.
  81944. */
  81945. _this.devicePosition = BABYLON.Vector3.Zero();
  81946. /**
  81947. * Represents device rotation in babylon space.
  81948. */
  81949. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81950. /**
  81951. * The scale of the device to be used when translating from device space to babylon space.
  81952. */
  81953. _this.deviceScaleFactor = 1;
  81954. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81955. _this._worldToDevice = BABYLON.Matrix.Identity();
  81956. /**
  81957. * References to the webVR controllers for the vrDevice.
  81958. */
  81959. _this.controllers = [];
  81960. /**
  81961. * Emits an event when a controller is attached.
  81962. */
  81963. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81964. /**
  81965. * Emits an event when a controller's mesh has been loaded;
  81966. */
  81967. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81968. /**
  81969. * If the rig cameras be used as parent instead of this camera.
  81970. */
  81971. _this.rigParenting = true;
  81972. _this._defaultHeight = undefined;
  81973. _this._workingVector = BABYLON.Vector3.Zero();
  81974. _this._oneVector = BABYLON.Vector3.One();
  81975. _this._workingMatrix = BABYLON.Matrix.Identity();
  81976. _this._cache.position = BABYLON.Vector3.Zero();
  81977. if (webVROptions.defaultHeight) {
  81978. _this._defaultHeight = webVROptions.defaultHeight;
  81979. _this.position.y = _this._defaultHeight;
  81980. }
  81981. _this.minZ = 0.1;
  81982. //legacy support - the compensation boolean was removed.
  81983. if (arguments.length === 5) {
  81984. _this.webVROptions = arguments[4];
  81985. }
  81986. // default webVR options
  81987. if (_this.webVROptions.trackPosition == undefined) {
  81988. _this.webVROptions.trackPosition = true;
  81989. }
  81990. if (_this.webVROptions.controllerMeshes == undefined) {
  81991. _this.webVROptions.controllerMeshes = true;
  81992. }
  81993. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81994. _this.webVROptions.defaultLightingOnControllers = true;
  81995. }
  81996. _this.rotationQuaternion = new BABYLON.Quaternion();
  81997. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81998. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81999. }
  82000. //enable VR
  82001. var engine = _this.getEngine();
  82002. _this._onVREnabled = function (success) { if (success) {
  82003. _this.initControllers();
  82004. } };
  82005. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  82006. engine.initWebVR().add(function (event) {
  82007. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  82008. return;
  82009. }
  82010. _this._vrDevice = event.vrDisplay;
  82011. //reset the rig parameters.
  82012. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  82013. if (_this._attached) {
  82014. _this.getEngine().enableVR();
  82015. }
  82016. });
  82017. if (typeof (VRFrameData) !== "undefined")
  82018. _this._frameData = new VRFrameData();
  82019. /**
  82020. * The idea behind the following lines:
  82021. * objects that have the camera as parent should actually have the rig cameras as a parent.
  82022. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  82023. * the second will not show it correctly.
  82024. *
  82025. * To solve this - each object that has the camera as parent will be added to a protected array.
  82026. * When the rig camera renders, it will take this array and set all of those to be its children.
  82027. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  82028. * Amazing!
  82029. */
  82030. scene.onBeforeCameraRenderObservable.add(function (camera) {
  82031. if (camera.parent === _this && _this.rigParenting) {
  82032. _this._descendants = _this.getDescendants(true, function (n) {
  82033. // don't take the cameras or the controllers!
  82034. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  82035. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  82036. return !isController && !isRigCamera;
  82037. });
  82038. _this._descendants.forEach(function (node) {
  82039. node.parent = camera;
  82040. });
  82041. }
  82042. });
  82043. scene.onAfterCameraRenderObservable.add(function (camera) {
  82044. if (camera.parent === _this && _this.rigParenting) {
  82045. _this._descendants.forEach(function (node) {
  82046. node.parent = _this;
  82047. });
  82048. }
  82049. });
  82050. return _this;
  82051. }
  82052. /**
  82053. * Gets the device distance from the ground in meters.
  82054. * @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.
  82055. */
  82056. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  82057. if (this._standingMatrix) {
  82058. // Add standing matrix offset to get real offset from ground in room
  82059. this._standingMatrix.getTranslationToRef(this._workingVector);
  82060. return this._deviceRoomPosition.y + this._workingVector.y;
  82061. }
  82062. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  82063. return this._defaultHeight || 0;
  82064. };
  82065. /**
  82066. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82067. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  82068. */
  82069. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  82070. var _this = this;
  82071. if (callback === void 0) { callback = function (bool) { }; }
  82072. // Use standing matrix if available
  82073. this.getEngine().initWebVRAsync().then(function (result) {
  82074. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  82075. callback(false);
  82076. }
  82077. else {
  82078. _this._standingMatrix = new BABYLON.Matrix();
  82079. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  82080. if (!_this.getScene().useRightHandedSystem) {
  82081. [2, 6, 8, 9, 14].forEach(function (num) {
  82082. if (_this._standingMatrix) {
  82083. _this._standingMatrix.m[num] *= -1;
  82084. }
  82085. });
  82086. }
  82087. callback(true);
  82088. }
  82089. });
  82090. };
  82091. /**
  82092. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82093. * @returns A promise with a boolean set to if the standing matrix is supported.
  82094. */
  82095. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  82096. var _this = this;
  82097. return new Promise(function (res, rej) {
  82098. _this.useStandingMatrix(function (supported) {
  82099. res(supported);
  82100. });
  82101. });
  82102. };
  82103. /**
  82104. * Disposes the camera
  82105. */
  82106. WebVRFreeCamera.prototype.dispose = function () {
  82107. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  82108. _super.prototype.dispose.call(this);
  82109. };
  82110. /**
  82111. * Gets a vrController by name.
  82112. * @param name The name of the controller to retreive
  82113. * @returns the controller matching the name specified or null if not found
  82114. */
  82115. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  82116. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  82117. var gp = _a[_i];
  82118. if (gp.hand === name) {
  82119. return gp;
  82120. }
  82121. }
  82122. return null;
  82123. };
  82124. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  82125. /**
  82126. * The controller corrisponding to the users left hand.
  82127. */
  82128. get: function () {
  82129. if (!this._leftController) {
  82130. this._leftController = this.getControllerByName("left");
  82131. }
  82132. return this._leftController;
  82133. },
  82134. enumerable: true,
  82135. configurable: true
  82136. });
  82137. ;
  82138. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  82139. /**
  82140. * The controller corrisponding to the users right hand.
  82141. */
  82142. get: function () {
  82143. if (!this._rightController) {
  82144. this._rightController = this.getControllerByName("right");
  82145. }
  82146. return this._rightController;
  82147. },
  82148. enumerable: true,
  82149. configurable: true
  82150. });
  82151. ;
  82152. /**
  82153. * Casts a ray forward from the vrCamera's gaze.
  82154. * @param length Length of the ray (default: 100)
  82155. * @returns the ray corrisponding to the gaze
  82156. */
  82157. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  82158. if (length === void 0) { length = 100; }
  82159. if (this.leftCamera) {
  82160. // Use left eye to avoid computation to compute center on every call
  82161. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  82162. }
  82163. else {
  82164. return _super.prototype.getForwardRay.call(this, length);
  82165. }
  82166. };
  82167. /**
  82168. * Updates the camera based on device's frame data
  82169. */
  82170. WebVRFreeCamera.prototype._checkInputs = function () {
  82171. if (this._vrDevice && this._vrDevice.isPresenting) {
  82172. this._vrDevice.getFrameData(this._frameData);
  82173. this.updateFromDevice(this._frameData.pose);
  82174. }
  82175. _super.prototype._checkInputs.call(this);
  82176. };
  82177. /**
  82178. * Updates the poseControlled values based on the input device pose.
  82179. * @param poseData Pose coming from the device
  82180. */
  82181. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  82182. if (poseData && poseData.orientation) {
  82183. this.rawPose = poseData;
  82184. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  82185. if (this.getScene().useRightHandedSystem) {
  82186. this._deviceRoomRotationQuaternion.z *= -1;
  82187. this._deviceRoomRotationQuaternion.w *= -1;
  82188. }
  82189. if (this.webVROptions.trackPosition && this.rawPose.position) {
  82190. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  82191. if (this.getScene().useRightHandedSystem) {
  82192. this._deviceRoomPosition.z *= -1;
  82193. }
  82194. }
  82195. }
  82196. };
  82197. /**
  82198. * WebVR's attach control will start broadcasting frames to the device.
  82199. * Note that in certain browsers (chrome for example) this function must be called
  82200. * within a user-interaction callback. Example:
  82201. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  82202. *
  82203. * @param element html element to attach the vrDevice to
  82204. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  82205. */
  82206. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  82207. _super.prototype.attachControl.call(this, element, noPreventDefault);
  82208. this._attached = true;
  82209. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  82210. if (this._vrDevice) {
  82211. this.getEngine().enableVR();
  82212. }
  82213. };
  82214. /**
  82215. * Detaches the camera from the html element and disables VR
  82216. *
  82217. * @param element html element to detach from
  82218. */
  82219. WebVRFreeCamera.prototype.detachControl = function (element) {
  82220. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82221. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82222. _super.prototype.detachControl.call(this, element);
  82223. this._attached = false;
  82224. this.getEngine().disableVR();
  82225. };
  82226. /**
  82227. * @returns the name of this class
  82228. */
  82229. WebVRFreeCamera.prototype.getClassName = function () {
  82230. return "WebVRFreeCamera";
  82231. };
  82232. /**
  82233. * Calls resetPose on the vrDisplay
  82234. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  82235. */
  82236. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  82237. //uses the vrDisplay's "resetPose()".
  82238. //pitch and roll won't be affected.
  82239. this._vrDevice.resetPose();
  82240. };
  82241. /**
  82242. * Updates the rig cameras (left and right eye)
  82243. */
  82244. WebVRFreeCamera.prototype._updateRigCameras = function () {
  82245. var camLeft = this._rigCameras[0];
  82246. var camRight = this._rigCameras[1];
  82247. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82248. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82249. camLeft.position.copyFrom(this._deviceRoomPosition);
  82250. camRight.position.copyFrom(this._deviceRoomPosition);
  82251. };
  82252. /**
  82253. * Updates the cached values of the camera
  82254. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  82255. */
  82256. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  82257. var _this = this;
  82258. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  82259. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  82260. if (!this.updateCacheCalled) {
  82261. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  82262. this.updateCacheCalled = true;
  82263. this.update();
  82264. }
  82265. // Set working vector to the device position in room space rotated by the new rotation
  82266. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  82267. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  82268. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  82269. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  82270. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  82271. // Add translation from anchor position
  82272. this._deviceToWorld.getTranslationToRef(this._workingVector);
  82273. this._workingVector.addInPlace(this.position);
  82274. this._workingVector.subtractInPlace(this._cache.position);
  82275. this._deviceToWorld.setTranslation(this._workingVector);
  82276. // Set an inverted matrix to be used when updating the camera
  82277. this._deviceToWorld.invertToRef(this._worldToDevice);
  82278. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  82279. this.controllers.forEach(function (controller) {
  82280. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  82281. controller.update();
  82282. });
  82283. }
  82284. if (!ignoreParentClass) {
  82285. _super.prototype._updateCache.call(this);
  82286. }
  82287. this.updateCacheCalled = false;
  82288. };
  82289. /**
  82290. * Updates the current device position and rotation in the babylon world
  82291. */
  82292. WebVRFreeCamera.prototype.update = function () {
  82293. // Get current device position in babylon world
  82294. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  82295. // Get current device rotation in babylon world
  82296. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  82297. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  82298. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82299. _super.prototype.update.call(this);
  82300. };
  82301. /**
  82302. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  82303. * @returns an identity matrix
  82304. */
  82305. WebVRFreeCamera.prototype._getViewMatrix = function () {
  82306. return BABYLON.Matrix.Identity();
  82307. };
  82308. /**
  82309. * This function is called by the two RIG cameras.
  82310. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  82311. */
  82312. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82313. var _this = this;
  82314. // Update the parent camera prior to using a child camera to avoid desynchronization
  82315. var parentCamera = this._cameraRigParams["parentCamera"];
  82316. parentCamera._updateCache();
  82317. //WebVR 1.1
  82318. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82319. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82320. if (!this.getScene().useRightHandedSystem) {
  82321. [2, 6, 8, 9, 14].forEach(function (num) {
  82322. _this._webvrViewMatrix.m[num] *= -1;
  82323. });
  82324. }
  82325. // update the camera rotation matrix
  82326. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82327. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82328. // Computing target and final matrix
  82329. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82330. // should the view matrix be updated with scale and position offset?
  82331. if (parentCamera.deviceScaleFactor !== 1) {
  82332. this._webvrViewMatrix.invert();
  82333. // scale the position, if set
  82334. if (parentCamera.deviceScaleFactor) {
  82335. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82336. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82337. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82338. }
  82339. this._webvrViewMatrix.invert();
  82340. }
  82341. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82342. return this._webvrViewMatrix;
  82343. };
  82344. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82345. var _this = this;
  82346. var parentCamera = this.parent;
  82347. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82348. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82349. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82350. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82351. //babylon compatible matrix
  82352. if (!this.getScene().useRightHandedSystem) {
  82353. [8, 9, 10, 11].forEach(function (num) {
  82354. _this._projectionMatrix.m[num] *= -1;
  82355. });
  82356. }
  82357. return this._projectionMatrix;
  82358. };
  82359. /**
  82360. * Initializes the controllers and their meshes
  82361. */
  82362. WebVRFreeCamera.prototype.initControllers = function () {
  82363. var _this = this;
  82364. this.controllers = [];
  82365. var manager = this.getScene().gamepadManager;
  82366. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82367. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82368. var webVrController = gamepad;
  82369. if (webVrController.defaultModel) {
  82370. webVrController.defaultModel.setEnabled(false);
  82371. }
  82372. if (webVrController.hand === "right") {
  82373. _this._rightController = null;
  82374. }
  82375. if (webVrController.hand === "left") {
  82376. _this._leftController = null;
  82377. }
  82378. var controllerIndex = _this.controllers.indexOf(webVrController);
  82379. if (controllerIndex !== -1) {
  82380. _this.controllers.splice(controllerIndex, 1);
  82381. }
  82382. }
  82383. });
  82384. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82385. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82386. var webVrController_1 = gamepad;
  82387. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82388. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82389. if (_this.webVROptions.controllerMeshes) {
  82390. if (webVrController_1.defaultModel) {
  82391. webVrController_1.defaultModel.setEnabled(true);
  82392. }
  82393. else {
  82394. // Load the meshes
  82395. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82396. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82397. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82398. if (_this.webVROptions.defaultLightingOnControllers) {
  82399. if (!_this._lightOnControllers) {
  82400. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82401. }
  82402. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82403. var children = mesh.getChildren();
  82404. if (children.length !== 0) {
  82405. children.forEach(function (mesh) {
  82406. light.includedOnlyMeshes.push(mesh);
  82407. activateLightOnSubMeshes_1(mesh, light);
  82408. });
  82409. }
  82410. };
  82411. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82412. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82413. }
  82414. });
  82415. }
  82416. }
  82417. webVrController_1.attachToPoseControlledCamera(_this);
  82418. // since this is async - sanity check. Is the controller already stored?
  82419. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82420. //add to the controllers array
  82421. _this.controllers.push(webVrController_1);
  82422. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82423. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82424. // So we're overriding setting left & right manually to be sure
  82425. var firstViveWandDetected = false;
  82426. for (var i = 0; i < _this.controllers.length; i++) {
  82427. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82428. if (!firstViveWandDetected) {
  82429. firstViveWandDetected = true;
  82430. _this.controllers[i].hand = "left";
  82431. }
  82432. else {
  82433. _this.controllers[i].hand = "right";
  82434. }
  82435. }
  82436. }
  82437. //did we find enough controllers? Great! let the developer know.
  82438. if (_this.controllers.length >= 2) {
  82439. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82440. }
  82441. }
  82442. }
  82443. });
  82444. };
  82445. return WebVRFreeCamera;
  82446. }(BABYLON.FreeCamera));
  82447. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82448. })(BABYLON || (BABYLON = {}));
  82449. //# sourceMappingURL=babylon.webVRCamera.js.map
  82450. "use strict";
  82451. var BABYLON;
  82452. (function (BABYLON) {
  82453. // We're mainly based on the logic defined into the FreeCamera code
  82454. /**
  82455. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82456. * being tilted forward or back and left or right.
  82457. */
  82458. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82459. __extends(DeviceOrientationCamera, _super);
  82460. /**
  82461. * Creates a new device orientation camera. @see DeviceOrientationCamera
  82462. * @param name The name of the camera
  82463. * @param position The start position camera
  82464. * @param scene The scene the camera belongs to
  82465. */
  82466. function DeviceOrientationCamera(name, position, scene) {
  82467. var _this = _super.call(this, name, position, scene) || this;
  82468. _this._quaternionCache = new BABYLON.Quaternion();
  82469. _this.inputs.addDeviceOrientation();
  82470. return _this;
  82471. }
  82472. /**
  82473. * Gets the current instance class name ("DeviceOrientationCamera").
  82474. * This helps avoiding instanceof at run time.
  82475. * @returns the class name
  82476. */
  82477. DeviceOrientationCamera.prototype.getClassName = function () {
  82478. return "DeviceOrientationCamera";
  82479. };
  82480. /**
  82481. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82482. */
  82483. DeviceOrientationCamera.prototype._checkInputs = function () {
  82484. _super.prototype._checkInputs.call(this);
  82485. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82486. if (this._initialQuaternion) {
  82487. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82488. }
  82489. };
  82490. /**
  82491. * Reset the camera to its default orientation on the specified axis only.
  82492. * @param axis The axis to reset
  82493. */
  82494. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82495. var _this = this;
  82496. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82497. //can only work if this camera has a rotation quaternion already.
  82498. if (!this.rotationQuaternion)
  82499. return;
  82500. if (!this._initialQuaternion) {
  82501. this._initialQuaternion = new BABYLON.Quaternion();
  82502. }
  82503. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82504. ['x', 'y', 'z'].forEach(function (axisName) {
  82505. if (!axis[axisName]) {
  82506. _this._initialQuaternion[axisName] = 0;
  82507. }
  82508. else {
  82509. _this._initialQuaternion[axisName] *= -1;
  82510. }
  82511. });
  82512. this._initialQuaternion.normalize();
  82513. //force rotation update
  82514. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82515. };
  82516. return DeviceOrientationCamera;
  82517. }(BABYLON.FreeCamera));
  82518. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82519. })(BABYLON || (BABYLON = {}));
  82520. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82521. "use strict";
  82522. var BABYLON;
  82523. (function (BABYLON) {
  82524. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82525. __extends(VRDeviceOrientationFreeCamera, _super);
  82526. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82527. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82528. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82529. var _this = _super.call(this, name, position, scene) || this;
  82530. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82531. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82532. return _this;
  82533. }
  82534. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82535. return "VRDeviceOrientationFreeCamera";
  82536. };
  82537. return VRDeviceOrientationFreeCamera;
  82538. }(BABYLON.DeviceOrientationCamera));
  82539. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82540. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82541. __extends(VRDeviceOrientationGamepadCamera, _super);
  82542. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82543. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82544. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82545. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82546. _this.inputs.addGamepad();
  82547. return _this;
  82548. }
  82549. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82550. return "VRDeviceOrientationGamepadCamera";
  82551. };
  82552. return VRDeviceOrientationGamepadCamera;
  82553. }(VRDeviceOrientationFreeCamera));
  82554. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82555. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82556. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82557. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82558. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82559. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82560. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82561. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82562. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82563. _this.inputs.addVRDeviceOrientation();
  82564. return _this;
  82565. }
  82566. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82567. return "VRDeviceOrientationArcRotateCamera";
  82568. };
  82569. return VRDeviceOrientationArcRotateCamera;
  82570. }(BABYLON.ArcRotateCamera));
  82571. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82572. })(BABYLON || (BABYLON = {}));
  82573. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82574. "use strict";
  82575. var BABYLON;
  82576. (function (BABYLON) {
  82577. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82578. __extends(AnaglyphFreeCamera, _super);
  82579. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82580. var _this = _super.call(this, name, position, scene) || this;
  82581. _this.interaxialDistance = interaxialDistance;
  82582. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82583. return _this;
  82584. }
  82585. AnaglyphFreeCamera.prototype.getClassName = function () {
  82586. return "AnaglyphFreeCamera";
  82587. };
  82588. return AnaglyphFreeCamera;
  82589. }(BABYLON.FreeCamera));
  82590. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82591. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82592. __extends(AnaglyphArcRotateCamera, _super);
  82593. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82594. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82595. _this.interaxialDistance = interaxialDistance;
  82596. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82597. return _this;
  82598. }
  82599. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82600. return "AnaglyphArcRotateCamera";
  82601. };
  82602. return AnaglyphArcRotateCamera;
  82603. }(BABYLON.ArcRotateCamera));
  82604. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82605. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82606. __extends(AnaglyphGamepadCamera, _super);
  82607. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82608. var _this = _super.call(this, name, position, scene) || this;
  82609. _this.interaxialDistance = interaxialDistance;
  82610. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82611. return _this;
  82612. }
  82613. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82614. return "AnaglyphGamepadCamera";
  82615. };
  82616. return AnaglyphGamepadCamera;
  82617. }(BABYLON.GamepadCamera));
  82618. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82619. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82620. __extends(AnaglyphUniversalCamera, _super);
  82621. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82622. var _this = _super.call(this, name, position, scene) || this;
  82623. _this.interaxialDistance = interaxialDistance;
  82624. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82625. return _this;
  82626. }
  82627. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82628. return "AnaglyphUniversalCamera";
  82629. };
  82630. return AnaglyphUniversalCamera;
  82631. }(BABYLON.UniversalCamera));
  82632. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82633. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82634. __extends(StereoscopicFreeCamera, _super);
  82635. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82636. var _this = _super.call(this, name, position, scene) || this;
  82637. _this.interaxialDistance = interaxialDistance;
  82638. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82639. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82640. return _this;
  82641. }
  82642. StereoscopicFreeCamera.prototype.getClassName = function () {
  82643. return "StereoscopicFreeCamera";
  82644. };
  82645. return StereoscopicFreeCamera;
  82646. }(BABYLON.FreeCamera));
  82647. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82648. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82649. __extends(StereoscopicArcRotateCamera, _super);
  82650. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82651. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82652. _this.interaxialDistance = interaxialDistance;
  82653. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82654. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82655. return _this;
  82656. }
  82657. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82658. return "StereoscopicArcRotateCamera";
  82659. };
  82660. return StereoscopicArcRotateCamera;
  82661. }(BABYLON.ArcRotateCamera));
  82662. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82663. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82664. __extends(StereoscopicGamepadCamera, _super);
  82665. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82666. var _this = _super.call(this, name, position, scene) || this;
  82667. _this.interaxialDistance = interaxialDistance;
  82668. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82669. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82670. return _this;
  82671. }
  82672. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82673. return "StereoscopicGamepadCamera";
  82674. };
  82675. return StereoscopicGamepadCamera;
  82676. }(BABYLON.GamepadCamera));
  82677. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82678. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82679. __extends(StereoscopicUniversalCamera, _super);
  82680. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82681. var _this = _super.call(this, name, position, scene) || this;
  82682. _this.interaxialDistance = interaxialDistance;
  82683. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82684. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82685. return _this;
  82686. }
  82687. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82688. return "StereoscopicUniversalCamera";
  82689. };
  82690. return StereoscopicUniversalCamera;
  82691. }(BABYLON.UniversalCamera));
  82692. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82693. })(BABYLON || (BABYLON = {}));
  82694. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82695. "use strict";
  82696. var BABYLON;
  82697. (function (BABYLON) {
  82698. var VRExperienceHelperGazer = /** @class */ (function () {
  82699. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82700. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82701. this.scene = scene;
  82702. this._pointerDownOnMeshAsked = false;
  82703. this._isActionableMesh = false;
  82704. this._teleportationRequestInitiated = false;
  82705. this._teleportationBackRequestInitiated = false;
  82706. this._dpadPressed = true;
  82707. this._activePointer = false;
  82708. this._id = VRExperienceHelperGazer._idCounter++;
  82709. // Gaze tracker
  82710. if (!gazeTrackerToClone) {
  82711. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82712. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82713. this._gazeTracker.isPickable = false;
  82714. this._gazeTracker.isVisible = false;
  82715. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82716. targetMat.specularColor = BABYLON.Color3.Black();
  82717. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82718. targetMat.backFaceCulling = false;
  82719. this._gazeTracker.material = targetMat;
  82720. }
  82721. else {
  82722. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82723. }
  82724. }
  82725. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82726. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82727. };
  82728. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82729. this._pointerDownOnMeshAsked = true;
  82730. if (this._currentMeshSelected && this._currentHit) {
  82731. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82732. }
  82733. };
  82734. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82735. if (this._currentMeshSelected && this._currentHit) {
  82736. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82737. }
  82738. this._pointerDownOnMeshAsked = false;
  82739. };
  82740. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82741. this._activePointer = true;
  82742. };
  82743. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82744. this._activePointer = false;
  82745. };
  82746. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82747. };
  82748. VRExperienceHelperGazer.prototype.dispose = function () {
  82749. this._interactionsEnabled = false;
  82750. this._teleportationEnabled = false;
  82751. };
  82752. VRExperienceHelperGazer._idCounter = 0;
  82753. return VRExperienceHelperGazer;
  82754. }());
  82755. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82756. __extends(VRExperienceHelperControllerGazer, _super);
  82757. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82758. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82759. _this.webVRController = webVRController;
  82760. // Laser pointer
  82761. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82762. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82763. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82764. laserPointerMaterial.alpha = 0.6;
  82765. _this._laserPointer.material = laserPointerMaterial;
  82766. _this._laserPointer.rotation.x = Math.PI / 2;
  82767. _this._laserPointer.position.z = -0.5;
  82768. _this._laserPointer.isVisible = false;
  82769. if (!webVRController.mesh) {
  82770. // Create an empty mesh that is used prior to loading the high quality model
  82771. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82772. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82773. preloadPointerPose.rotation.x = -0.7;
  82774. preloadMesh.addChild(preloadPointerPose);
  82775. webVRController.attachToMesh(preloadMesh);
  82776. }
  82777. _this._setLaserPointerParent(webVRController.mesh);
  82778. return _this;
  82779. }
  82780. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82781. return this.webVRController.getForwardRay(length);
  82782. };
  82783. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82784. _super.prototype._activatePointer.call(this);
  82785. this._laserPointer.isVisible = true;
  82786. };
  82787. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82788. _super.prototype._deactivatePointer.call(this);
  82789. this._laserPointer.isVisible = false;
  82790. };
  82791. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82792. this._laserPointer.material.emissiveColor = color;
  82793. };
  82794. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82795. var makeNotPick = function (root) {
  82796. root.name += " laserPointer";
  82797. root.getChildMeshes().forEach(function (c) {
  82798. makeNotPick(c);
  82799. });
  82800. };
  82801. makeNotPick(mesh);
  82802. var childMeshes = mesh.getChildMeshes();
  82803. this.webVRController._pointingPoseNode = null;
  82804. for (var i = 0; i < childMeshes.length; i++) {
  82805. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82806. mesh = childMeshes[i];
  82807. this.webVRController._pointingPoseNode = mesh;
  82808. break;
  82809. }
  82810. }
  82811. this._laserPointer.parent = mesh;
  82812. };
  82813. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82814. this._laserPointer.scaling.y = distance;
  82815. this._laserPointer.position.z = -distance / 2;
  82816. };
  82817. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82818. _super.prototype.dispose.call(this);
  82819. this._laserPointer.dispose();
  82820. };
  82821. return VRExperienceHelperControllerGazer;
  82822. }(VRExperienceHelperGazer));
  82823. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82824. __extends(VRExperienceHelperCameraGazer, _super);
  82825. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82826. var _this = _super.call(this, scene) || this;
  82827. _this.getCamera = getCamera;
  82828. return _this;
  82829. }
  82830. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82831. var camera = this.getCamera();
  82832. if (camera) {
  82833. return camera.getForwardRay(length);
  82834. }
  82835. else {
  82836. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82837. }
  82838. };
  82839. return VRExperienceHelperCameraGazer;
  82840. }(VRExperienceHelperGazer));
  82841. /**
  82842. * Helps to quickly add VR support to an existing scene.
  82843. * See http://doc.babylonjs.com/how_to/webvr_helper
  82844. */
  82845. var VRExperienceHelper = /** @class */ (function () {
  82846. /**
  82847. * Instantiates a VRExperienceHelper.
  82848. * Helps to quickly add VR support to an existing scene.
  82849. * @param scene The scene the VRExperienceHelper belongs to.
  82850. * @param webVROptions Options to modify the vr experience helper's behavior.
  82851. */
  82852. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82853. if (webVROptions === void 0) { webVROptions = {}; }
  82854. var _this = this;
  82855. this.webVROptions = webVROptions;
  82856. // Can the system support WebVR, even if a headset isn't plugged in?
  82857. this._webVRsupported = false;
  82858. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82859. this._webVRready = false;
  82860. // Are we waiting for the requestPresent callback to complete?
  82861. this._webVRrequesting = false;
  82862. // Are we presenting to the headset right now?
  82863. this._webVRpresenting = false;
  82864. // Are we presenting in the fullscreen fallback?
  82865. this._fullscreenVRpresenting = false;
  82866. /**
  82867. * Observable raised when entering VR.
  82868. */
  82869. this.onEnteringVRObservable = new BABYLON.Observable();
  82870. /**
  82871. * Observable raised when exiting VR.
  82872. */
  82873. this.onExitingVRObservable = new BABYLON.Observable();
  82874. /**
  82875. * Observable raised when controller mesh is loaded.
  82876. */
  82877. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82878. this._useCustomVRButton = false;
  82879. this._teleportationRequested = false;
  82880. this._teleportActive = false;
  82881. this._floorMeshesCollection = [];
  82882. this._rotationAllowed = true;
  82883. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82884. this._rotationRightAsked = false;
  82885. this._rotationLeftAsked = false;
  82886. this._isDefaultTeleportationTarget = true;
  82887. this._teleportationFillColor = "#444444";
  82888. this._teleportationBorderColor = "#FFFFFF";
  82889. this._rotationAngle = 0;
  82890. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82891. this._padSensibilityUp = 0.65;
  82892. this._padSensibilityDown = 0.35;
  82893. this.leftController = null;
  82894. this.rightController = null;
  82895. /**
  82896. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82897. */
  82898. this.onNewMeshSelected = new BABYLON.Observable();
  82899. /**
  82900. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82901. */
  82902. this.onNewMeshPicked = new BABYLON.Observable();
  82903. /**
  82904. * Observable raised before camera teleportation
  82905. */
  82906. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82907. /**
  82908. * Observable raised after camera teleportation
  82909. */
  82910. this.onAfterCameraTeleport = new BABYLON.Observable();
  82911. /**
  82912. * Observable raised when current selected mesh gets unselected
  82913. */
  82914. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82915. /**
  82916. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82917. */
  82918. this.teleportationEnabled = true;
  82919. this._teleportationInitialized = false;
  82920. this._interactionsEnabled = false;
  82921. this._interactionsRequested = false;
  82922. this._displayGaze = true;
  82923. this._displayLaserPointer = true;
  82924. this._onResize = function () {
  82925. _this.moveButtonToBottomRight();
  82926. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82927. _this.exitVR();
  82928. }
  82929. };
  82930. this._onFullscreenChange = function () {
  82931. if (document.fullscreen !== undefined) {
  82932. _this._fullscreenVRpresenting = document.fullscreen;
  82933. }
  82934. else if (document.mozFullScreen !== undefined) {
  82935. _this._fullscreenVRpresenting = document.mozFullScreen;
  82936. }
  82937. else if (document.webkitIsFullScreen !== undefined) {
  82938. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82939. }
  82940. else if (document.msIsFullScreen !== undefined) {
  82941. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82942. }
  82943. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82944. _this.exitVR();
  82945. if (!_this._useCustomVRButton) {
  82946. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82947. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82948. }
  82949. }
  82950. };
  82951. this.beforeRender = function () {
  82952. if (_this.leftController && _this.leftController._activePointer) {
  82953. _this._castRayAndSelectObject(_this.leftController);
  82954. }
  82955. if (_this.rightController && _this.rightController._activePointer) {
  82956. _this._castRayAndSelectObject(_this.rightController);
  82957. }
  82958. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82959. _this._castRayAndSelectObject(_this._cameraGazer);
  82960. }
  82961. else {
  82962. _this._cameraGazer._gazeTracker.isVisible = false;
  82963. }
  82964. };
  82965. this._onNewGamepadConnected = function (gamepad) {
  82966. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82967. if (gamepad.leftStick) {
  82968. gamepad.onleftstickchanged(function (stickValues) {
  82969. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82970. // Listening to classic/xbox gamepad only if no VR controller is active
  82971. if ((!_this.leftController && !_this.rightController) ||
  82972. ((_this.leftController && !_this.leftController._activePointer) &&
  82973. (_this.rightController && !_this.rightController._activePointer))) {
  82974. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82975. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82976. }
  82977. }
  82978. });
  82979. }
  82980. if (gamepad.rightStick) {
  82981. gamepad.onrightstickchanged(function (stickValues) {
  82982. if (_this._teleportationInitialized) {
  82983. _this._checkRotate(stickValues, _this._cameraGazer);
  82984. }
  82985. });
  82986. }
  82987. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82988. gamepad.onbuttondown(function (buttonPressed) {
  82989. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82990. _this._cameraGazer._selectionPointerDown();
  82991. }
  82992. });
  82993. gamepad.onbuttonup(function (buttonPressed) {
  82994. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82995. _this._cameraGazer._selectionPointerUp();
  82996. }
  82997. });
  82998. }
  82999. }
  83000. else {
  83001. var webVRController = gamepad;
  83002. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  83003. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  83004. _this.rightController = controller;
  83005. }
  83006. else {
  83007. _this.leftController = controller;
  83008. }
  83009. _this._tryEnableInteractionOnController(controller);
  83010. }
  83011. };
  83012. // 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
  83013. this._tryEnableInteractionOnController = function (controller) {
  83014. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  83015. _this._enableInteractionOnController(controller);
  83016. }
  83017. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  83018. _this._enableTeleportationOnController(controller);
  83019. }
  83020. };
  83021. this._onNewGamepadDisconnected = function (gamepad) {
  83022. if (gamepad instanceof BABYLON.WebVRController) {
  83023. if (gamepad.hand === "left" && _this.leftController != null) {
  83024. _this.leftController.dispose();
  83025. _this.leftController = null;
  83026. }
  83027. if (gamepad.hand === "right" && _this.rightController != null) {
  83028. _this.rightController.dispose();
  83029. _this.rightController = null;
  83030. }
  83031. }
  83032. };
  83033. this._workingVector = BABYLON.Vector3.Zero();
  83034. this._workingQuaternion = BABYLON.Quaternion.Identity();
  83035. this._workingMatrix = BABYLON.Matrix.Identity();
  83036. this._scene = scene;
  83037. this._canvas = scene.getEngine().getRenderingCanvas();
  83038. // Parse options
  83039. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  83040. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  83041. }
  83042. if (webVROptions.createDeviceOrientationCamera === undefined) {
  83043. webVROptions.createDeviceOrientationCamera = true;
  83044. }
  83045. if (webVROptions.defaultHeight === undefined) {
  83046. webVROptions.defaultHeight = 1.7;
  83047. }
  83048. if (webVROptions.useCustomVRButton) {
  83049. this._useCustomVRButton = true;
  83050. if (webVROptions.customVRButton) {
  83051. this._btnVR = webVROptions.customVRButton;
  83052. }
  83053. }
  83054. if (webVROptions.rayLength) {
  83055. this._rayLength = webVROptions.rayLength;
  83056. }
  83057. this._defaultHeight = webVROptions.defaultHeight;
  83058. if (webVROptions.positionScale) {
  83059. this._rayLength *= webVROptions.positionScale;
  83060. this._defaultHeight *= webVROptions.positionScale;
  83061. }
  83062. // Set position
  83063. if (this._scene.activeCamera) {
  83064. this._position = this._scene.activeCamera.position.clone();
  83065. }
  83066. else {
  83067. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  83068. }
  83069. // Set non-vr camera
  83070. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  83071. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  83072. // Copy data from existing camera
  83073. if (this._scene.activeCamera) {
  83074. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  83075. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  83076. // Set rotation from previous camera
  83077. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  83078. var targetCamera = this._scene.activeCamera;
  83079. if (targetCamera.rotationQuaternion) {
  83080. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  83081. }
  83082. else {
  83083. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  83084. }
  83085. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  83086. }
  83087. }
  83088. this._scene.activeCamera = this._deviceOrientationCamera;
  83089. if (this._canvas) {
  83090. this._scene.activeCamera.attachControl(this._canvas);
  83091. }
  83092. }
  83093. else {
  83094. this._existingCamera = this._scene.activeCamera;
  83095. }
  83096. // Create VR cameras
  83097. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83098. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  83099. }
  83100. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  83101. this._webVRCamera.useStandingMatrix();
  83102. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  83103. // Create default button
  83104. if (!this._useCustomVRButton) {
  83105. this._btnVR = document.createElement("BUTTON");
  83106. this._btnVR.className = "babylonVRicon";
  83107. this._btnVR.id = "babylonVRiconbtn";
  83108. this._btnVR.title = "Click to switch to VR";
  83109. 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) }";
  83110. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  83111. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  83112. // css += ".babylonVRicon.vrdisplaysupported { }";
  83113. // css += ".babylonVRicon.vrdisplayready { }";
  83114. // css += ".babylonVRicon.vrdisplayrequesting { }";
  83115. var style = document.createElement('style');
  83116. style.appendChild(document.createTextNode(css));
  83117. document.getElementsByTagName('head')[0].appendChild(style);
  83118. this.moveButtonToBottomRight();
  83119. }
  83120. // VR button click event
  83121. if (this._btnVR) {
  83122. this._btnVR.addEventListener("click", function () {
  83123. if (!_this.isInVRMode) {
  83124. _this.enterVR();
  83125. }
  83126. else {
  83127. _this.exitVR();
  83128. }
  83129. });
  83130. }
  83131. // Window events
  83132. window.addEventListener("resize", this._onResize);
  83133. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  83134. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  83135. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  83136. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  83137. // Display vr button when headset is connected
  83138. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83139. this.displayVRButton();
  83140. }
  83141. else {
  83142. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  83143. if (e.vrDisplay) {
  83144. _this.displayVRButton();
  83145. }
  83146. });
  83147. }
  83148. // Exiting VR mode using 'ESC' key on desktop
  83149. this._onKeyDown = function (event) {
  83150. if (event.keyCode === 27 && _this.isInVRMode) {
  83151. _this.exitVR();
  83152. }
  83153. };
  83154. document.addEventListener("keydown", this._onKeyDown);
  83155. // Exiting VR mode double tapping the touch screen
  83156. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  83157. if (_this.isInVRMode) {
  83158. _this.exitVR();
  83159. if (_this._fullscreenVRpresenting) {
  83160. _this._scene.getEngine().switchFullscreen(true);
  83161. }
  83162. }
  83163. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  83164. // Listen for WebVR display changes
  83165. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  83166. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  83167. this._onVRRequestPresentStart = function () {
  83168. _this._webVRrequesting = true;
  83169. _this.updateButtonVisibility();
  83170. };
  83171. this._onVRRequestPresentComplete = function (success) {
  83172. _this._webVRrequesting = false;
  83173. _this.updateButtonVisibility();
  83174. };
  83175. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  83176. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  83177. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  83178. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83179. scene.onDisposeObservable.add(function () {
  83180. _this.dispose();
  83181. });
  83182. // Gamepad connection events
  83183. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  83184. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  83185. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  83186. this.updateButtonVisibility();
  83187. //create easing functions
  83188. this._circleEase = new BABYLON.CircleEase();
  83189. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83190. }
  83191. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  83192. /** Return this.onEnteringVRObservable
  83193. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  83194. */
  83195. get: function () {
  83196. return this.onEnteringVRObservable;
  83197. },
  83198. enumerable: true,
  83199. configurable: true
  83200. });
  83201. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  83202. /** Return this.onExitingVRObservable
  83203. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  83204. */
  83205. get: function () {
  83206. return this.onExitingVRObservable;
  83207. },
  83208. enumerable: true,
  83209. configurable: true
  83210. });
  83211. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  83212. /** Return this.onControllerMeshLoadedObservable
  83213. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  83214. */
  83215. get: function () {
  83216. return this.onControllerMeshLoadedObservable;
  83217. },
  83218. enumerable: true,
  83219. configurable: true
  83220. });
  83221. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  83222. /**
  83223. * The mesh used to display where the user is going to teleport.
  83224. */
  83225. get: function () {
  83226. return this._teleportationTarget;
  83227. },
  83228. /**
  83229. * Sets the mesh to be used to display where the user is going to teleport.
  83230. */
  83231. set: function (value) {
  83232. if (value) {
  83233. value.name = "teleportationTarget";
  83234. this._isDefaultTeleportationTarget = false;
  83235. this._teleportationTarget = value;
  83236. }
  83237. },
  83238. enumerable: true,
  83239. configurable: true
  83240. });
  83241. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  83242. /**
  83243. * The mesh used to display where the user is selecting,
  83244. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  83245. * See http://doc.babylonjs.com/resources/baking_transformations
  83246. */
  83247. get: function () {
  83248. return this._cameraGazer._gazeTracker;
  83249. },
  83250. set: function (value) {
  83251. if (value) {
  83252. this._cameraGazer._gazeTracker = value;
  83253. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  83254. this._cameraGazer._gazeTracker.isPickable = false;
  83255. this._cameraGazer._gazeTracker.isVisible = false;
  83256. this._cameraGazer._gazeTracker.name = "gazeTracker";
  83257. if (this.leftController) {
  83258. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83259. }
  83260. if (this.rightController) {
  83261. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83262. }
  83263. }
  83264. },
  83265. enumerable: true,
  83266. configurable: true
  83267. });
  83268. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  83269. /**
  83270. * If the ray of the gaze should be displayed.
  83271. */
  83272. get: function () {
  83273. return this._displayGaze;
  83274. },
  83275. /**
  83276. * Sets if the ray of the gaze should be displayed.
  83277. */
  83278. set: function (value) {
  83279. this._displayGaze = value;
  83280. if (!value) {
  83281. this._cameraGazer._gazeTracker.isVisible = false;
  83282. if (this.leftController) {
  83283. this.leftController._gazeTracker.isVisible = false;
  83284. }
  83285. if (this.rightController) {
  83286. this.rightController._gazeTracker.isVisible = false;
  83287. }
  83288. }
  83289. },
  83290. enumerable: true,
  83291. configurable: true
  83292. });
  83293. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  83294. /**
  83295. * If the ray of the LaserPointer should be displayed.
  83296. */
  83297. get: function () {
  83298. return this._displayLaserPointer;
  83299. },
  83300. /**
  83301. * Sets if the ray of the LaserPointer should be displayed.
  83302. */
  83303. set: function (value) {
  83304. this._displayLaserPointer = value;
  83305. if (!value) {
  83306. if (this.rightController) {
  83307. this.rightController._deactivatePointer();
  83308. this.rightController._gazeTracker.isVisible = false;
  83309. }
  83310. if (this.leftController) {
  83311. this.leftController._deactivatePointer();
  83312. this.leftController._gazeTracker.isVisible = false;
  83313. }
  83314. }
  83315. else {
  83316. if (this.rightController) {
  83317. this.rightController._activatePointer();
  83318. }
  83319. else if (this.leftController) {
  83320. this.leftController._activatePointer();
  83321. }
  83322. }
  83323. },
  83324. enumerable: true,
  83325. configurable: true
  83326. });
  83327. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83328. /**
  83329. * The deviceOrientationCamera used as the camera when not in VR.
  83330. */
  83331. get: function () {
  83332. return this._deviceOrientationCamera;
  83333. },
  83334. enumerable: true,
  83335. configurable: true
  83336. });
  83337. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83338. /**
  83339. * Based on the current WebVR support, returns the current VR camera used.
  83340. */
  83341. get: function () {
  83342. if (this._webVRready) {
  83343. return this._webVRCamera;
  83344. }
  83345. else {
  83346. return this._scene.activeCamera;
  83347. }
  83348. },
  83349. enumerable: true,
  83350. configurable: true
  83351. });
  83352. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83353. /**
  83354. * The webVRCamera which is used when in VR.
  83355. */
  83356. get: function () {
  83357. return this._webVRCamera;
  83358. },
  83359. enumerable: true,
  83360. configurable: true
  83361. });
  83362. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83363. /**
  83364. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83365. */
  83366. get: function () {
  83367. return this._vrDeviceOrientationCamera;
  83368. },
  83369. enumerable: true,
  83370. configurable: true
  83371. });
  83372. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83373. get: function () {
  83374. var result = this._cameraGazer._teleportationRequestInitiated
  83375. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83376. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83377. return result;
  83378. },
  83379. enumerable: true,
  83380. configurable: true
  83381. });
  83382. // Raised when one of the controller has loaded successfully its associated default mesh
  83383. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83384. if (this.leftController && this.leftController.webVRController == webVRController) {
  83385. if (webVRController.mesh) {
  83386. this.leftController._setLaserPointerParent(webVRController.mesh);
  83387. }
  83388. }
  83389. if (this.rightController && this.rightController.webVRController == webVRController) {
  83390. if (webVRController.mesh) {
  83391. this.rightController._setLaserPointerParent(webVRController.mesh);
  83392. }
  83393. }
  83394. try {
  83395. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83396. }
  83397. catch (err) {
  83398. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83399. }
  83400. };
  83401. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83402. /**
  83403. * Gets a value indicating if we are currently in VR mode.
  83404. */
  83405. get: function () {
  83406. return this._webVRpresenting || this._fullscreenVRpresenting;
  83407. },
  83408. enumerable: true,
  83409. configurable: true
  83410. });
  83411. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83412. var vrDisplay = this._scene.getEngine().getVRDevice();
  83413. if (vrDisplay) {
  83414. var wasPresenting = this._webVRpresenting;
  83415. // A VR display is connected
  83416. this._webVRpresenting = vrDisplay.isPresenting;
  83417. if (wasPresenting && !this._webVRpresenting)
  83418. this.exitVR();
  83419. }
  83420. else {
  83421. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83422. }
  83423. this.updateButtonVisibility();
  83424. };
  83425. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83426. this._webVRsupported = eventArgs.vrSupported;
  83427. this._webVRready = !!eventArgs.vrDisplay;
  83428. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83429. this.updateButtonVisibility();
  83430. };
  83431. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83432. if (this._canvas && !this._useCustomVRButton) {
  83433. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83434. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83435. }
  83436. };
  83437. VRExperienceHelper.prototype.displayVRButton = function () {
  83438. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83439. document.body.appendChild(this._btnVR);
  83440. this._btnVRDisplayed = true;
  83441. }
  83442. };
  83443. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83444. if (!this._btnVR || this._useCustomVRButton) {
  83445. return;
  83446. }
  83447. this._btnVR.className = "babylonVRicon";
  83448. if (this.isInVRMode) {
  83449. this._btnVR.className += " vrdisplaypresenting";
  83450. }
  83451. else {
  83452. if (this._webVRready)
  83453. this._btnVR.className += " vrdisplayready";
  83454. if (this._webVRsupported)
  83455. this._btnVR.className += " vrdisplaysupported";
  83456. if (this._webVRrequesting)
  83457. this._btnVR.className += " vrdisplayrequesting";
  83458. }
  83459. };
  83460. /**
  83461. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83462. * Otherwise, will use the fullscreen API.
  83463. */
  83464. VRExperienceHelper.prototype.enterVR = function () {
  83465. if (this.onEnteringVRObservable) {
  83466. try {
  83467. this.onEnteringVRObservable.notifyObservers(this);
  83468. }
  83469. catch (err) {
  83470. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83471. }
  83472. }
  83473. if (this._scene.activeCamera) {
  83474. this._position = this._scene.activeCamera.position.clone();
  83475. // make sure that we return to the last active camera
  83476. this._existingCamera = this._scene.activeCamera;
  83477. }
  83478. if (this._webVRrequesting)
  83479. return;
  83480. // If WebVR is supported and a headset is connected
  83481. if (this._webVRready) {
  83482. if (!this._webVRpresenting) {
  83483. this._webVRCamera.position = this._position;
  83484. this._scene.activeCamera = this._webVRCamera;
  83485. }
  83486. }
  83487. else if (this._vrDeviceOrientationCamera) {
  83488. this._vrDeviceOrientationCamera.position = this._position;
  83489. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83490. this._scene.getEngine().switchFullscreen(true);
  83491. this.updateButtonVisibility();
  83492. }
  83493. if (this._scene.activeCamera && this._canvas) {
  83494. this._scene.activeCamera.attachControl(this._canvas);
  83495. }
  83496. if (this._interactionsEnabled) {
  83497. this._scene.registerBeforeRender(this.beforeRender);
  83498. }
  83499. };
  83500. /**
  83501. * Attempt to exit VR, or fullscreen.
  83502. */
  83503. VRExperienceHelper.prototype.exitVR = function () {
  83504. if (this.onExitingVRObservable) {
  83505. try {
  83506. this.onExitingVRObservable.notifyObservers(this);
  83507. }
  83508. catch (err) {
  83509. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83510. }
  83511. }
  83512. if (this._webVRpresenting) {
  83513. this._scene.getEngine().disableVR();
  83514. }
  83515. if (this._scene.activeCamera) {
  83516. this._position = this._scene.activeCamera.position.clone();
  83517. }
  83518. if (this._deviceOrientationCamera) {
  83519. this._deviceOrientationCamera.position = this._position;
  83520. this._scene.activeCamera = this._deviceOrientationCamera;
  83521. if (this._canvas) {
  83522. this._scene.activeCamera.attachControl(this._canvas);
  83523. }
  83524. }
  83525. else if (this._existingCamera) {
  83526. this._existingCamera.position = this._position;
  83527. this._scene.activeCamera = this._existingCamera;
  83528. }
  83529. this.updateButtonVisibility();
  83530. if (this._interactionsEnabled) {
  83531. this._scene.unregisterBeforeRender(this.beforeRender);
  83532. }
  83533. };
  83534. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83535. /**
  83536. * The position of the vr experience helper.
  83537. */
  83538. get: function () {
  83539. return this._position;
  83540. },
  83541. /**
  83542. * Sets the position of the vr experience helper.
  83543. */
  83544. set: function (value) {
  83545. this._position = value;
  83546. if (this._scene.activeCamera) {
  83547. this._scene.activeCamera.position = value;
  83548. }
  83549. },
  83550. enumerable: true,
  83551. configurable: true
  83552. });
  83553. /**
  83554. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83555. */
  83556. VRExperienceHelper.prototype.enableInteractions = function () {
  83557. var _this = this;
  83558. if (!this._interactionsEnabled) {
  83559. this._interactionsRequested = true;
  83560. if (this.leftController) {
  83561. this._enableInteractionOnController(this.leftController);
  83562. }
  83563. if (this.rightController) {
  83564. this._enableInteractionOnController(this.rightController);
  83565. }
  83566. this.raySelectionPredicate = function (mesh) {
  83567. return mesh.isVisible;
  83568. };
  83569. this.meshSelectionPredicate = function (mesh) {
  83570. return true;
  83571. };
  83572. this._raySelectionPredicate = function (mesh) {
  83573. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83574. && mesh.name.indexOf("teleportationTarget") === -1
  83575. && mesh.name.indexOf("torusTeleportation") === -1
  83576. && mesh.name.indexOf("laserPointer") === -1)) {
  83577. return _this.raySelectionPredicate(mesh);
  83578. }
  83579. return false;
  83580. };
  83581. this._interactionsEnabled = true;
  83582. }
  83583. };
  83584. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83585. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83586. if (this._floorMeshesCollection[i].id === mesh.id) {
  83587. return true;
  83588. }
  83589. }
  83590. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83591. return true;
  83592. }
  83593. return false;
  83594. };
  83595. /**
  83596. * Adds a floor mesh to be used for teleportation.
  83597. * @param floorMesh the mesh to be used for teleportation.
  83598. */
  83599. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83600. if (!this._floorMeshesCollection) {
  83601. return;
  83602. }
  83603. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83604. return;
  83605. }
  83606. this._floorMeshesCollection.push(floorMesh);
  83607. };
  83608. /**
  83609. * Removes a floor mesh from being used for teleportation.
  83610. * @param floorMesh the mesh to be removed.
  83611. */
  83612. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83613. if (!this._floorMeshesCollection) {
  83614. return;
  83615. }
  83616. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83617. if (meshIndex !== -1) {
  83618. this._floorMeshesCollection.splice(meshIndex, 1);
  83619. }
  83620. };
  83621. /**
  83622. * Enables interactions and teleportation using the VR controllers and gaze.
  83623. * @param vrTeleportationOptions options to modify teleportation behavior.
  83624. */
  83625. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83626. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83627. if (!this._teleportationInitialized) {
  83628. this._teleportationRequested = true;
  83629. this.enableInteractions();
  83630. if (vrTeleportationOptions.floorMeshName) {
  83631. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83632. }
  83633. if (vrTeleportationOptions.floorMeshes) {
  83634. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83635. }
  83636. if (this.leftController != null) {
  83637. this._enableTeleportationOnController(this.leftController);
  83638. }
  83639. if (this.rightController != null) {
  83640. this._enableTeleportationOnController(this.rightController);
  83641. }
  83642. // Creates an image processing post process for the vignette not relying
  83643. // on the main scene configuration for image processing to reduce setup and spaces
  83644. // (gamma/linear) conflicts.
  83645. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83646. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83647. imageProcessingConfiguration.vignetteEnabled = true;
  83648. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83649. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83650. this._teleportationInitialized = true;
  83651. if (this._isDefaultTeleportationTarget) {
  83652. this._createTeleportationCircles();
  83653. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83654. }
  83655. }
  83656. };
  83657. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83658. var _this = this;
  83659. var controllerMesh = controller.webVRController.mesh;
  83660. if (controllerMesh) {
  83661. controller._interactionsEnabled = true;
  83662. controller._activatePointer();
  83663. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83664. // Enabling / disabling laserPointer
  83665. if (_this._displayLaserPointer && stateObject.value === 1) {
  83666. if (controller._activePointer) {
  83667. controller._deactivatePointer();
  83668. }
  83669. else {
  83670. controller._activatePointer();
  83671. }
  83672. if (_this.displayGaze) {
  83673. controller._gazeTracker.isVisible = controller._activePointer;
  83674. }
  83675. }
  83676. });
  83677. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83678. if (!controller._pointerDownOnMeshAsked) {
  83679. if (stateObject.value > _this._padSensibilityUp) {
  83680. controller._selectionPointerDown();
  83681. }
  83682. }
  83683. else if (stateObject.value < _this._padSensibilityDown) {
  83684. controller._selectionPointerUp();
  83685. }
  83686. });
  83687. }
  83688. };
  83689. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83690. // Dont teleport if another gaze already requested teleportation
  83691. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83692. return;
  83693. }
  83694. if (!gazer._teleportationRequestInitiated) {
  83695. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83696. gazer._activatePointer();
  83697. gazer._teleportationRequestInitiated = true;
  83698. }
  83699. }
  83700. else {
  83701. // Listening to the proper controller values changes to confirm teleportation
  83702. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83703. if (this._teleportActive) {
  83704. this._teleportCamera(this._haloCenter);
  83705. }
  83706. gazer._teleportationRequestInitiated = false;
  83707. }
  83708. }
  83709. };
  83710. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83711. // Only rotate when user is not currently selecting a teleportation location
  83712. if (gazer._teleportationRequestInitiated) {
  83713. return;
  83714. }
  83715. if (!this._rotationLeftAsked) {
  83716. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83717. this._rotationLeftAsked = true;
  83718. if (this._rotationAllowed) {
  83719. this._rotateCamera(false);
  83720. }
  83721. }
  83722. }
  83723. else {
  83724. if (stateObject.x > -this._padSensibilityDown) {
  83725. this._rotationLeftAsked = false;
  83726. }
  83727. }
  83728. if (!this._rotationRightAsked) {
  83729. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83730. this._rotationRightAsked = true;
  83731. if (this._rotationAllowed) {
  83732. this._rotateCamera(true);
  83733. }
  83734. }
  83735. }
  83736. else {
  83737. if (stateObject.x < this._padSensibilityDown) {
  83738. this._rotationRightAsked = false;
  83739. }
  83740. }
  83741. };
  83742. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83743. // Only teleport backwards when user is not currently selecting a teleportation location
  83744. if (gazer._teleportationRequestInitiated) {
  83745. return;
  83746. }
  83747. // Teleport backwards
  83748. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83749. if (!gazer._teleportationBackRequestInitiated) {
  83750. if (!this.currentVRCamera) {
  83751. return;
  83752. }
  83753. // Get rotation and position of the current camera
  83754. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83755. var position = this.currentVRCamera.position;
  83756. // If the camera has device position, use that instead
  83757. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83758. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83759. position = this.currentVRCamera.devicePosition;
  83760. }
  83761. // Get matrix with only the y rotation of the device rotation
  83762. rotation.toEulerAnglesToRef(this._workingVector);
  83763. this._workingVector.z = 0;
  83764. this._workingVector.x = 0;
  83765. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83766. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83767. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83768. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83769. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83770. var ray = new BABYLON.Ray(position, this._workingVector);
  83771. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83772. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83773. this._teleportCamera(hit.pickedPoint);
  83774. }
  83775. gazer._teleportationBackRequestInitiated = true;
  83776. }
  83777. }
  83778. else {
  83779. gazer._teleportationBackRequestInitiated = false;
  83780. }
  83781. };
  83782. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83783. var _this = this;
  83784. var controllerMesh = controller.webVRController.mesh;
  83785. if (controllerMesh) {
  83786. if (!controller._interactionsEnabled) {
  83787. this._enableInteractionOnController(controller);
  83788. }
  83789. controller._interactionsEnabled = true;
  83790. controller._teleportationEnabled = true;
  83791. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83792. controller._dpadPressed = false;
  83793. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83794. controller._dpadPressed = stateObject.pressed;
  83795. if (!controller._dpadPressed) {
  83796. _this._rotationLeftAsked = false;
  83797. _this._rotationRightAsked = false;
  83798. controller._teleportationBackRequestInitiated = false;
  83799. }
  83800. });
  83801. }
  83802. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83803. if (_this.teleportationEnabled) {
  83804. _this._checkTeleportBackwards(stateObject, controller);
  83805. _this._checkTeleportWithRay(stateObject, controller);
  83806. }
  83807. _this._checkRotate(stateObject, controller);
  83808. });
  83809. }
  83810. };
  83811. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83812. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83813. this._teleportationTarget.isPickable = false;
  83814. var length = 512;
  83815. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83816. dynamicTexture.hasAlpha = true;
  83817. var context = dynamicTexture.getContext();
  83818. var centerX = length / 2;
  83819. var centerY = length / 2;
  83820. var radius = 200;
  83821. context.beginPath();
  83822. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83823. context.fillStyle = this._teleportationFillColor;
  83824. context.fill();
  83825. context.lineWidth = 10;
  83826. context.strokeStyle = this._teleportationBorderColor;
  83827. context.stroke();
  83828. context.closePath();
  83829. dynamicTexture.update();
  83830. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83831. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83832. this._teleportationTarget.material = teleportationCircleMaterial;
  83833. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83834. torus.isPickable = false;
  83835. torus.parent = this._teleportationTarget;
  83836. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83837. var keys = [];
  83838. keys.push({
  83839. frame: 0,
  83840. value: 0
  83841. });
  83842. keys.push({
  83843. frame: 30,
  83844. value: 0.4
  83845. });
  83846. keys.push({
  83847. frame: 60,
  83848. value: 0
  83849. });
  83850. animationInnerCircle.setKeys(keys);
  83851. var easingFunction = new BABYLON.SineEase();
  83852. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83853. animationInnerCircle.setEasingFunction(easingFunction);
  83854. torus.animations = [];
  83855. torus.animations.push(animationInnerCircle);
  83856. this._scene.beginAnimation(torus, 0, 60, true);
  83857. this._hideTeleportationTarget();
  83858. };
  83859. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83860. this._teleportActive = true;
  83861. if (this._teleportationInitialized) {
  83862. this._teleportationTarget.isVisible = true;
  83863. if (this._isDefaultTeleportationTarget) {
  83864. this._teleportationTarget.getChildren()[0].isVisible = true;
  83865. }
  83866. }
  83867. };
  83868. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83869. this._teleportActive = false;
  83870. if (this._teleportationInitialized) {
  83871. this._teleportationTarget.isVisible = false;
  83872. if (this._isDefaultTeleportationTarget) {
  83873. this._teleportationTarget.getChildren()[0].isVisible = false;
  83874. }
  83875. }
  83876. };
  83877. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83878. var _this = this;
  83879. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83880. return;
  83881. }
  83882. if (right) {
  83883. this._rotationAngle++;
  83884. }
  83885. else {
  83886. this._rotationAngle--;
  83887. }
  83888. this.currentVRCamera.animations = [];
  83889. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83890. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83891. var animationRotationKeys = [];
  83892. animationRotationKeys.push({
  83893. frame: 0,
  83894. value: this.currentVRCamera.rotationQuaternion
  83895. });
  83896. animationRotationKeys.push({
  83897. frame: 6,
  83898. value: target
  83899. });
  83900. animationRotation.setKeys(animationRotationKeys);
  83901. animationRotation.setEasingFunction(this._circleEase);
  83902. this.currentVRCamera.animations.push(animationRotation);
  83903. this._postProcessMove.animations = [];
  83904. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83905. var vignetteWeightKeys = [];
  83906. vignetteWeightKeys.push({
  83907. frame: 0,
  83908. value: 0
  83909. });
  83910. vignetteWeightKeys.push({
  83911. frame: 3,
  83912. value: 4
  83913. });
  83914. vignetteWeightKeys.push({
  83915. frame: 6,
  83916. value: 0
  83917. });
  83918. animationPP.setKeys(vignetteWeightKeys);
  83919. animationPP.setEasingFunction(this._circleEase);
  83920. this._postProcessMove.animations.push(animationPP);
  83921. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83922. var vignetteStretchKeys = [];
  83923. vignetteStretchKeys.push({
  83924. frame: 0,
  83925. value: 0
  83926. });
  83927. vignetteStretchKeys.push({
  83928. frame: 3,
  83929. value: 10
  83930. });
  83931. vignetteStretchKeys.push({
  83932. frame: 6,
  83933. value: 0
  83934. });
  83935. animationPP2.setKeys(vignetteStretchKeys);
  83936. animationPP2.setEasingFunction(this._circleEase);
  83937. this._postProcessMove.animations.push(animationPP2);
  83938. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83939. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83940. this._postProcessMove.samples = 4;
  83941. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83942. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83943. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83944. });
  83945. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83946. };
  83947. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83948. if (hit.pickedPoint) {
  83949. if (gazer._teleportationRequestInitiated) {
  83950. this._displayTeleportationTarget();
  83951. this._haloCenter.copyFrom(hit.pickedPoint);
  83952. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83953. }
  83954. var pickNormal = hit.getNormal(true, false);
  83955. if (pickNormal) {
  83956. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83957. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83958. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83959. }
  83960. this._teleportationTarget.position.y += 0.1;
  83961. }
  83962. };
  83963. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83964. var _this = this;
  83965. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83966. return;
  83967. }
  83968. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83969. // offset of the headset from the anchor.
  83970. if (this.webVRCamera.leftCamera) {
  83971. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83972. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83973. location.subtractToRef(this._workingVector, this._workingVector);
  83974. }
  83975. else {
  83976. this._workingVector.copyFrom(location);
  83977. }
  83978. // Add height to account for user's height offset
  83979. if (this.isInVRMode) {
  83980. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83981. }
  83982. else {
  83983. this._workingVector.y += this._defaultHeight;
  83984. }
  83985. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83986. // Create animation from the camera's position to the new location
  83987. this.currentVRCamera.animations = [];
  83988. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83989. var animationCameraTeleportationKeys = [{
  83990. frame: 0,
  83991. value: this.currentVRCamera.position
  83992. },
  83993. {
  83994. frame: 11,
  83995. value: this._workingVector
  83996. }
  83997. ];
  83998. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83999. animationCameraTeleportation.setEasingFunction(this._circleEase);
  84000. this.currentVRCamera.animations.push(animationCameraTeleportation);
  84001. this._postProcessMove.animations = [];
  84002. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84003. var vignetteWeightKeys = [];
  84004. vignetteWeightKeys.push({
  84005. frame: 0,
  84006. value: 0
  84007. });
  84008. vignetteWeightKeys.push({
  84009. frame: 5,
  84010. value: 8
  84011. });
  84012. vignetteWeightKeys.push({
  84013. frame: 11,
  84014. value: 0
  84015. });
  84016. animationPP.setKeys(vignetteWeightKeys);
  84017. this._postProcessMove.animations.push(animationPP);
  84018. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84019. var vignetteStretchKeys = [];
  84020. vignetteStretchKeys.push({
  84021. frame: 0,
  84022. value: 0
  84023. });
  84024. vignetteStretchKeys.push({
  84025. frame: 5,
  84026. value: 10
  84027. });
  84028. vignetteStretchKeys.push({
  84029. frame: 11,
  84030. value: 0
  84031. });
  84032. animationPP2.setKeys(vignetteStretchKeys);
  84033. this._postProcessMove.animations.push(animationPP2);
  84034. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84035. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84036. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84037. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  84038. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84039. });
  84040. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  84041. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  84042. });
  84043. this._hideTeleportationTarget();
  84044. };
  84045. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  84046. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84047. return;
  84048. }
  84049. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  84050. // Moving the gazeTracker on the mesh face targetted
  84051. if (hit && hit.pickedPoint) {
  84052. if (this._displayGaze) {
  84053. var multiplier = 1;
  84054. gazer._gazeTracker.isVisible = true;
  84055. if (gazer._isActionableMesh) {
  84056. multiplier = 3;
  84057. }
  84058. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  84059. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  84060. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  84061. var pickNormal = hit.getNormal();
  84062. // To avoid z-fighting
  84063. var deltaFighting = 0.002;
  84064. if (pickNormal) {
  84065. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84066. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84067. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  84068. }
  84069. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  84070. if (gazer._gazeTracker.position.x < 0) {
  84071. gazer._gazeTracker.position.x += deltaFighting;
  84072. }
  84073. else {
  84074. gazer._gazeTracker.position.x -= deltaFighting;
  84075. }
  84076. if (gazer._gazeTracker.position.y < 0) {
  84077. gazer._gazeTracker.position.y += deltaFighting;
  84078. }
  84079. else {
  84080. gazer._gazeTracker.position.y -= deltaFighting;
  84081. }
  84082. if (gazer._gazeTracker.position.z < 0) {
  84083. gazer._gazeTracker.position.z += deltaFighting;
  84084. }
  84085. else {
  84086. gazer._gazeTracker.position.z -= deltaFighting;
  84087. }
  84088. }
  84089. // Changing the size of the laser pointer based on the distance from the targetted point
  84090. gazer._updatePointerDistance(hit.distance);
  84091. }
  84092. else {
  84093. gazer._gazeTracker.isVisible = false;
  84094. }
  84095. if (hit && hit.pickedMesh) {
  84096. gazer._currentHit = hit;
  84097. if (gazer._pointerDownOnMeshAsked) {
  84098. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  84099. }
  84100. // The object selected is the floor, we're in a teleportation scenario
  84101. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  84102. // Moving the teleportation area to this targetted point
  84103. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  84104. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  84105. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84106. }
  84107. gazer._currentMeshSelected = null;
  84108. if (gazer._teleportationRequestInitiated) {
  84109. this._moveTeleportationSelectorTo(hit, gazer);
  84110. }
  84111. return;
  84112. }
  84113. // If not, we're in a selection scenario
  84114. //this._teleportationAllowed = false;
  84115. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  84116. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  84117. this.onNewMeshPicked.notifyObservers(hit);
  84118. gazer._currentMeshSelected = hit.pickedMesh;
  84119. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  84120. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  84121. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  84122. gazer._isActionableMesh = true;
  84123. }
  84124. else {
  84125. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84126. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84127. gazer._isActionableMesh = false;
  84128. }
  84129. try {
  84130. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  84131. }
  84132. catch (err) {
  84133. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  84134. }
  84135. }
  84136. else {
  84137. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84138. gazer._currentMeshSelected = null;
  84139. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84140. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84141. }
  84142. }
  84143. }
  84144. else {
  84145. gazer._currentHit = null;
  84146. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84147. gazer._currentMeshSelected = null;
  84148. //this._teleportationAllowed = false;
  84149. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84150. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84151. }
  84152. };
  84153. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  84154. if (mesh) {
  84155. this.onSelectedMeshUnselected.notifyObservers(mesh);
  84156. }
  84157. };
  84158. /**
  84159. * Sets the color of the laser ray from the vr controllers.
  84160. * @param color new color for the ray.
  84161. */
  84162. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  84163. if (this.leftController) {
  84164. this.leftController._setLaserPointerColor(color);
  84165. }
  84166. if (this.rightController) {
  84167. this.rightController._setLaserPointerColor(color);
  84168. }
  84169. };
  84170. /**
  84171. * Sets the color of the ray from the vr headsets gaze.
  84172. * @param color new color for the ray.
  84173. */
  84174. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  84175. if (!this._cameraGazer._gazeTracker.material) {
  84176. return;
  84177. }
  84178. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  84179. if (this.leftController) {
  84180. this.leftController._gazeTracker.material.emissiveColor = color;
  84181. }
  84182. if (this.rightController) {
  84183. this.rightController._gazeTracker.material.emissiveColor = color;
  84184. }
  84185. };
  84186. /**
  84187. * Exits VR and disposes of the vr experience helper
  84188. */
  84189. VRExperienceHelper.prototype.dispose = function () {
  84190. if (this.isInVRMode) {
  84191. this.exitVR();
  84192. }
  84193. if (this._postProcessMove) {
  84194. this._postProcessMove.dispose();
  84195. }
  84196. if (this._webVRCamera) {
  84197. this._webVRCamera.dispose();
  84198. }
  84199. if (this._vrDeviceOrientationCamera) {
  84200. this._vrDeviceOrientationCamera.dispose();
  84201. }
  84202. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  84203. document.body.removeChild(this._btnVR);
  84204. }
  84205. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  84206. this._deviceOrientationCamera.dispose();
  84207. }
  84208. if (this._cameraGazer) {
  84209. this._cameraGazer.dispose();
  84210. }
  84211. if (this.leftController) {
  84212. this.leftController.dispose();
  84213. }
  84214. if (this.rightController) {
  84215. this.rightController.dispose();
  84216. }
  84217. if (this._teleportationTarget) {
  84218. this._teleportationTarget.dispose();
  84219. }
  84220. this._floorMeshesCollection = [];
  84221. document.removeEventListener("keydown", this._onKeyDown);
  84222. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84223. window.removeEventListener("resize", this._onResize);
  84224. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  84225. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  84226. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  84227. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  84228. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  84229. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  84230. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  84231. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84232. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  84233. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  84234. this._scene.unregisterBeforeRender(this.beforeRender);
  84235. };
  84236. /**
  84237. * Gets the name of the VRExperienceHelper class
  84238. * @returns "VRExperienceHelper"
  84239. */
  84240. VRExperienceHelper.prototype.getClassName = function () {
  84241. return "VRExperienceHelper";
  84242. };
  84243. return VRExperienceHelper;
  84244. }());
  84245. BABYLON.VRExperienceHelper = VRExperienceHelper;
  84246. })(BABYLON || (BABYLON = {}));
  84247. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  84248. "use strict";
  84249. // Mainly based on these 2 articles :
  84250. // 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
  84251. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  84252. var BABYLON;
  84253. (function (BABYLON) {
  84254. var JoystickAxis;
  84255. (function (JoystickAxis) {
  84256. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  84257. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  84258. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  84259. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  84260. var VirtualJoystick = /** @class */ (function () {
  84261. function VirtualJoystick(leftJoystick) {
  84262. var _this = this;
  84263. if (leftJoystick) {
  84264. this._leftJoystick = true;
  84265. }
  84266. else {
  84267. this._leftJoystick = false;
  84268. }
  84269. VirtualJoystick._globalJoystickIndex++;
  84270. // By default left & right arrow keys are moving the X
  84271. // and up & down keys are moving the Y
  84272. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84273. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84274. this.reverseLeftRight = false;
  84275. this.reverseUpDown = false;
  84276. // collections of pointers
  84277. this._touches = new BABYLON.StringDictionary();
  84278. this.deltaPosition = BABYLON.Vector3.Zero();
  84279. this._joystickSensibility = 25;
  84280. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84281. this._onResize = function (evt) {
  84282. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84283. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84284. if (VirtualJoystick.vjCanvas) {
  84285. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  84286. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  84287. }
  84288. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  84289. };
  84290. // injecting a canvas element on top of the canvas 3D game
  84291. if (!VirtualJoystick.vjCanvas) {
  84292. window.addEventListener("resize", this._onResize, false);
  84293. VirtualJoystick.vjCanvas = document.createElement("canvas");
  84294. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84295. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84296. VirtualJoystick.vjCanvas.width = window.innerWidth;
  84297. VirtualJoystick.vjCanvas.height = window.innerHeight;
  84298. VirtualJoystick.vjCanvas.style.width = "100%";
  84299. VirtualJoystick.vjCanvas.style.height = "100%";
  84300. VirtualJoystick.vjCanvas.style.position = "absolute";
  84301. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  84302. VirtualJoystick.vjCanvas.style.top = "0px";
  84303. VirtualJoystick.vjCanvas.style.left = "0px";
  84304. VirtualJoystick.vjCanvas.style.zIndex = "5";
  84305. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  84306. // Support for jQuery PEP polyfill
  84307. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  84308. var context = VirtualJoystick.vjCanvas.getContext('2d');
  84309. if (!context) {
  84310. throw new Error("Unable to create canvas for virtual joystick");
  84311. }
  84312. VirtualJoystick.vjCanvasContext = context;
  84313. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84314. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84315. document.body.appendChild(VirtualJoystick.vjCanvas);
  84316. }
  84317. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84318. this.pressed = false;
  84319. // default joystick color
  84320. this._joystickColor = "cyan";
  84321. this._joystickPointerID = -1;
  84322. // current joystick position
  84323. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84324. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84325. // origin joystick position
  84326. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84327. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84328. this._onPointerDownHandlerRef = function (evt) {
  84329. _this._onPointerDown(evt);
  84330. };
  84331. this._onPointerMoveHandlerRef = function (evt) {
  84332. _this._onPointerMove(evt);
  84333. };
  84334. this._onPointerUpHandlerRef = function (evt) {
  84335. _this._onPointerUp(evt);
  84336. };
  84337. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84338. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84339. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84340. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84341. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84342. evt.preventDefault(); // Disables system menu
  84343. }, false);
  84344. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84345. }
  84346. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84347. this._joystickSensibility = newJoystickSensibility;
  84348. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84349. };
  84350. VirtualJoystick.prototype._onPointerDown = function (e) {
  84351. var positionOnScreenCondition;
  84352. e.preventDefault();
  84353. if (this._leftJoystick === true) {
  84354. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84355. }
  84356. else {
  84357. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84358. }
  84359. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84360. // First contact will be dedicated to the virtual joystick
  84361. this._joystickPointerID = e.pointerId;
  84362. this._joystickPointerStartPos.x = e.clientX;
  84363. this._joystickPointerStartPos.y = e.clientY;
  84364. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84365. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84366. this._deltaJoystickVector.x = 0;
  84367. this._deltaJoystickVector.y = 0;
  84368. this.pressed = true;
  84369. this._touches.add(e.pointerId.toString(), e);
  84370. }
  84371. else {
  84372. // You can only trigger the action buttons with a joystick declared
  84373. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84374. this._action();
  84375. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84376. }
  84377. }
  84378. };
  84379. VirtualJoystick.prototype._onPointerMove = function (e) {
  84380. // If the current pointer is the one associated to the joystick (first touch contact)
  84381. if (this._joystickPointerID == e.pointerId) {
  84382. this._joystickPointerPos.x = e.clientX;
  84383. this._joystickPointerPos.y = e.clientY;
  84384. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84385. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84386. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84387. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84388. switch (this._axisTargetedByLeftAndRight) {
  84389. case JoystickAxis.X:
  84390. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84391. break;
  84392. case JoystickAxis.Y:
  84393. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84394. break;
  84395. case JoystickAxis.Z:
  84396. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84397. break;
  84398. }
  84399. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84400. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84401. switch (this._axisTargetedByUpAndDown) {
  84402. case JoystickAxis.X:
  84403. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84404. break;
  84405. case JoystickAxis.Y:
  84406. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84407. break;
  84408. case JoystickAxis.Z:
  84409. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84410. break;
  84411. }
  84412. }
  84413. else {
  84414. var data = this._touches.get(e.pointerId.toString());
  84415. if (data) {
  84416. data.x = e.clientX;
  84417. data.y = e.clientY;
  84418. }
  84419. }
  84420. };
  84421. VirtualJoystick.prototype._onPointerUp = function (e) {
  84422. if (this._joystickPointerID == e.pointerId) {
  84423. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84424. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84425. this._joystickPointerID = -1;
  84426. this.pressed = false;
  84427. }
  84428. else {
  84429. var touch = this._touches.get(e.pointerId.toString());
  84430. if (touch) {
  84431. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84432. }
  84433. }
  84434. this._deltaJoystickVector.x = 0;
  84435. this._deltaJoystickVector.y = 0;
  84436. this._touches.remove(e.pointerId.toString());
  84437. };
  84438. /**
  84439. * Change the color of the virtual joystick
  84440. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84441. */
  84442. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84443. this._joystickColor = newColor;
  84444. };
  84445. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84446. this._action = action;
  84447. };
  84448. // Define which axis you'd like to control for left & right
  84449. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84450. switch (axis) {
  84451. case JoystickAxis.X:
  84452. case JoystickAxis.Y:
  84453. case JoystickAxis.Z:
  84454. this._axisTargetedByLeftAndRight = axis;
  84455. break;
  84456. default:
  84457. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84458. break;
  84459. }
  84460. };
  84461. // Define which axis you'd like to control for up & down
  84462. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84463. switch (axis) {
  84464. case JoystickAxis.X:
  84465. case JoystickAxis.Y:
  84466. case JoystickAxis.Z:
  84467. this._axisTargetedByUpAndDown = axis;
  84468. break;
  84469. default:
  84470. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84471. break;
  84472. }
  84473. };
  84474. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84475. var _this = this;
  84476. if (this.pressed) {
  84477. this._touches.forEach(function (key, touch) {
  84478. if (touch.pointerId === _this._joystickPointerID) {
  84479. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84480. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84481. VirtualJoystick.vjCanvasContext.beginPath();
  84482. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84483. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84484. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84485. VirtualJoystick.vjCanvasContext.stroke();
  84486. VirtualJoystick.vjCanvasContext.closePath();
  84487. VirtualJoystick.vjCanvasContext.beginPath();
  84488. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84489. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84490. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84491. VirtualJoystick.vjCanvasContext.stroke();
  84492. VirtualJoystick.vjCanvasContext.closePath();
  84493. VirtualJoystick.vjCanvasContext.beginPath();
  84494. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84495. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84496. VirtualJoystick.vjCanvasContext.stroke();
  84497. VirtualJoystick.vjCanvasContext.closePath();
  84498. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84499. }
  84500. else {
  84501. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84502. VirtualJoystick.vjCanvasContext.beginPath();
  84503. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84504. VirtualJoystick.vjCanvasContext.beginPath();
  84505. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84506. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84507. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84508. VirtualJoystick.vjCanvasContext.stroke();
  84509. VirtualJoystick.vjCanvasContext.closePath();
  84510. touch.prevX = touch.x;
  84511. touch.prevY = touch.y;
  84512. }
  84513. ;
  84514. });
  84515. }
  84516. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84517. };
  84518. VirtualJoystick.prototype.releaseCanvas = function () {
  84519. if (VirtualJoystick.vjCanvas) {
  84520. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84521. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84522. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84523. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84524. window.removeEventListener("resize", this._onResize);
  84525. document.body.removeChild(VirtualJoystick.vjCanvas);
  84526. VirtualJoystick.vjCanvas = null;
  84527. }
  84528. };
  84529. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84530. VirtualJoystick._globalJoystickIndex = 0;
  84531. return VirtualJoystick;
  84532. }());
  84533. BABYLON.VirtualJoystick = VirtualJoystick;
  84534. })(BABYLON || (BABYLON = {}));
  84535. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84536. "use strict";
  84537. var BABYLON;
  84538. (function (BABYLON) {
  84539. // We're mainly based on the logic defined into the FreeCamera code
  84540. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84541. __extends(VirtualJoysticksCamera, _super);
  84542. function VirtualJoysticksCamera(name, position, scene) {
  84543. var _this = _super.call(this, name, position, scene) || this;
  84544. _this.inputs.addVirtualJoystick();
  84545. return _this;
  84546. }
  84547. VirtualJoysticksCamera.prototype.getClassName = function () {
  84548. return "VirtualJoysticksCamera";
  84549. };
  84550. return VirtualJoysticksCamera;
  84551. }(BABYLON.FreeCamera));
  84552. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84553. })(BABYLON || (BABYLON = {}));
  84554. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84555. "use strict";
  84556. var BABYLON;
  84557. (function (BABYLON) {
  84558. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84559. function FreeCameraVirtualJoystickInput() {
  84560. }
  84561. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84562. return this._leftjoystick;
  84563. };
  84564. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84565. return this._rightjoystick;
  84566. };
  84567. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84568. if (this._leftjoystick) {
  84569. var camera = this.camera;
  84570. var speed = camera._computeLocalCameraSpeed() * 50;
  84571. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84572. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84573. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84574. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84575. if (!this._leftjoystick.pressed) {
  84576. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84577. }
  84578. if (!this._rightjoystick.pressed) {
  84579. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84580. }
  84581. }
  84582. };
  84583. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84584. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84585. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84586. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84587. this._leftjoystick.setJoystickSensibility(0.15);
  84588. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84589. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84590. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84591. this._rightjoystick.reverseUpDown = true;
  84592. this._rightjoystick.setJoystickSensibility(0.05);
  84593. this._rightjoystick.setJoystickColor("yellow");
  84594. };
  84595. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84596. this._leftjoystick.releaseCanvas();
  84597. this._rightjoystick.releaseCanvas();
  84598. };
  84599. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84600. return "FreeCameraVirtualJoystickInput";
  84601. };
  84602. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84603. return "virtualJoystick";
  84604. };
  84605. return FreeCameraVirtualJoystickInput;
  84606. }());
  84607. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84608. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84609. })(BABYLON || (BABYLON = {}));
  84610. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84611. "use strict";
  84612. var BABYLON;
  84613. (function (BABYLON) {
  84614. var SimplificationSettings = /** @class */ (function () {
  84615. function SimplificationSettings(quality, distance, optimizeMesh) {
  84616. this.quality = quality;
  84617. this.distance = distance;
  84618. this.optimizeMesh = optimizeMesh;
  84619. }
  84620. return SimplificationSettings;
  84621. }());
  84622. BABYLON.SimplificationSettings = SimplificationSettings;
  84623. var SimplificationQueue = /** @class */ (function () {
  84624. function SimplificationQueue() {
  84625. this.running = false;
  84626. this._simplificationArray = [];
  84627. }
  84628. SimplificationQueue.prototype.addTask = function (task) {
  84629. this._simplificationArray.push(task);
  84630. };
  84631. SimplificationQueue.prototype.executeNext = function () {
  84632. var task = this._simplificationArray.pop();
  84633. if (task) {
  84634. this.running = true;
  84635. this.runSimplification(task);
  84636. }
  84637. else {
  84638. this.running = false;
  84639. }
  84640. };
  84641. SimplificationQueue.prototype.runSimplification = function (task) {
  84642. var _this = this;
  84643. if (task.parallelProcessing) {
  84644. //parallel simplifier
  84645. task.settings.forEach(function (setting) {
  84646. var simplifier = _this.getSimplifier(task);
  84647. simplifier.simplify(setting, function (newMesh) {
  84648. task.mesh.addLODLevel(setting.distance, newMesh);
  84649. newMesh.isVisible = true;
  84650. //check if it is the last
  84651. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84652. //all done, run the success callback.
  84653. task.successCallback();
  84654. }
  84655. _this.executeNext();
  84656. });
  84657. });
  84658. }
  84659. else {
  84660. //single simplifier.
  84661. var simplifier = this.getSimplifier(task);
  84662. var runDecimation = function (setting, callback) {
  84663. simplifier.simplify(setting, function (newMesh) {
  84664. task.mesh.addLODLevel(setting.distance, newMesh);
  84665. newMesh.isVisible = true;
  84666. //run the next quality level
  84667. callback();
  84668. });
  84669. };
  84670. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84671. runDecimation(task.settings[loop.index], function () {
  84672. loop.executeNext();
  84673. });
  84674. }, function () {
  84675. //execution ended, run the success callback.
  84676. if (task.successCallback) {
  84677. task.successCallback();
  84678. }
  84679. _this.executeNext();
  84680. });
  84681. }
  84682. };
  84683. SimplificationQueue.prototype.getSimplifier = function (task) {
  84684. switch (task.simplificationType) {
  84685. case SimplificationType.QUADRATIC:
  84686. default:
  84687. return new QuadraticErrorSimplification(task.mesh);
  84688. }
  84689. };
  84690. return SimplificationQueue;
  84691. }());
  84692. BABYLON.SimplificationQueue = SimplificationQueue;
  84693. /**
  84694. * The implemented types of simplification.
  84695. * At the moment only Quadratic Error Decimation is implemented.
  84696. */
  84697. var SimplificationType;
  84698. (function (SimplificationType) {
  84699. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84700. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84701. var DecimationTriangle = /** @class */ (function () {
  84702. function DecimationTriangle(vertices) {
  84703. this.vertices = vertices;
  84704. this.error = new Array(4);
  84705. this.deleted = false;
  84706. this.isDirty = false;
  84707. this.deletePending = false;
  84708. this.borderFactor = 0;
  84709. }
  84710. return DecimationTriangle;
  84711. }());
  84712. BABYLON.DecimationTriangle = DecimationTriangle;
  84713. var DecimationVertex = /** @class */ (function () {
  84714. function DecimationVertex(position, id) {
  84715. this.position = position;
  84716. this.id = id;
  84717. this.isBorder = true;
  84718. this.q = new QuadraticMatrix();
  84719. this.triangleCount = 0;
  84720. this.triangleStart = 0;
  84721. this.originalOffsets = [];
  84722. }
  84723. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84724. this.position.copyFrom(newPosition);
  84725. };
  84726. return DecimationVertex;
  84727. }());
  84728. BABYLON.DecimationVertex = DecimationVertex;
  84729. var QuadraticMatrix = /** @class */ (function () {
  84730. function QuadraticMatrix(data) {
  84731. this.data = new Array(10);
  84732. for (var i = 0; i < 10; ++i) {
  84733. if (data && data[i]) {
  84734. this.data[i] = data[i];
  84735. }
  84736. else {
  84737. this.data[i] = 0;
  84738. }
  84739. }
  84740. }
  84741. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84742. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84743. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84744. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84745. return det;
  84746. };
  84747. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84748. for (var i = 0; i < 10; ++i) {
  84749. this.data[i] += matrix.data[i];
  84750. }
  84751. };
  84752. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84753. for (var i = 0; i < 10; ++i) {
  84754. this.data[i] += data[i];
  84755. }
  84756. };
  84757. QuadraticMatrix.prototype.add = function (matrix) {
  84758. var m = new QuadraticMatrix();
  84759. for (var i = 0; i < 10; ++i) {
  84760. m.data[i] = this.data[i] + matrix.data[i];
  84761. }
  84762. return m;
  84763. };
  84764. QuadraticMatrix.FromData = function (a, b, c, d) {
  84765. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84766. };
  84767. //returning an array to avoid garbage collection
  84768. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84769. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84770. };
  84771. return QuadraticMatrix;
  84772. }());
  84773. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84774. var Reference = /** @class */ (function () {
  84775. function Reference(vertexId, triangleId) {
  84776. this.vertexId = vertexId;
  84777. this.triangleId = triangleId;
  84778. }
  84779. return Reference;
  84780. }());
  84781. BABYLON.Reference = Reference;
  84782. /**
  84783. * An implementation of the Quadratic Error simplification algorithm.
  84784. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84785. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84786. * @author RaananW
  84787. */
  84788. var QuadraticErrorSimplification = /** @class */ (function () {
  84789. function QuadraticErrorSimplification(_mesh) {
  84790. this._mesh = _mesh;
  84791. this.syncIterations = 5000;
  84792. this.aggressiveness = 7;
  84793. this.decimationIterations = 100;
  84794. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84795. }
  84796. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84797. var _this = this;
  84798. this.initDecimatedMesh();
  84799. //iterating through the submeshes array, one after the other.
  84800. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84801. _this.initWithMesh(loop.index, function () {
  84802. _this.runDecimation(settings, loop.index, function () {
  84803. loop.executeNext();
  84804. });
  84805. }, settings.optimizeMesh);
  84806. }, function () {
  84807. setTimeout(function () {
  84808. successCallback(_this._reconstructedMesh);
  84809. }, 0);
  84810. });
  84811. };
  84812. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84813. var _this = this;
  84814. var targetCount = ~~(this.triangles.length * settings.quality);
  84815. var deletedTriangles = 0;
  84816. var triangleCount = this.triangles.length;
  84817. var iterationFunction = function (iteration, callback) {
  84818. setTimeout(function () {
  84819. if (iteration % 5 === 0) {
  84820. _this.updateMesh(iteration === 0);
  84821. }
  84822. for (var i = 0; i < _this.triangles.length; ++i) {
  84823. _this.triangles[i].isDirty = false;
  84824. }
  84825. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84826. var trianglesIterator = function (i) {
  84827. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84828. var t = _this.triangles[tIdx];
  84829. if (!t)
  84830. return;
  84831. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84832. return;
  84833. }
  84834. for (var j = 0; j < 3; ++j) {
  84835. if (t.error[j] < threshold) {
  84836. var deleted0 = [];
  84837. var deleted1 = [];
  84838. var v0 = t.vertices[j];
  84839. var v1 = t.vertices[(j + 1) % 3];
  84840. if (v0.isBorder || v1.isBorder)
  84841. continue;
  84842. var p = BABYLON.Vector3.Zero();
  84843. var n = BABYLON.Vector3.Zero();
  84844. var uv = BABYLON.Vector2.Zero();
  84845. var color = new BABYLON.Color4(0, 0, 0, 1);
  84846. _this.calculateError(v0, v1, p, n, uv, color);
  84847. var delTr = new Array();
  84848. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84849. continue;
  84850. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84851. continue;
  84852. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84853. continue;
  84854. var uniqueArray = new Array();
  84855. delTr.forEach(function (deletedT) {
  84856. if (uniqueArray.indexOf(deletedT) === -1) {
  84857. deletedT.deletePending = true;
  84858. uniqueArray.push(deletedT);
  84859. }
  84860. });
  84861. if (uniqueArray.length % 2 !== 0) {
  84862. continue;
  84863. }
  84864. v0.q = v1.q.add(v0.q);
  84865. v0.updatePosition(p);
  84866. var tStart = _this.references.length;
  84867. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84868. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84869. var tCount = _this.references.length - tStart;
  84870. if (tCount <= v0.triangleCount) {
  84871. if (tCount) {
  84872. for (var c = 0; c < tCount; c++) {
  84873. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84874. }
  84875. }
  84876. }
  84877. else {
  84878. v0.triangleStart = tStart;
  84879. }
  84880. v0.triangleCount = tCount;
  84881. break;
  84882. }
  84883. }
  84884. };
  84885. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84886. }, 0);
  84887. };
  84888. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84889. if (triangleCount - deletedTriangles <= targetCount)
  84890. loop.breakLoop();
  84891. else {
  84892. iterationFunction(loop.index, function () {
  84893. loop.executeNext();
  84894. });
  84895. }
  84896. }, function () {
  84897. setTimeout(function () {
  84898. //reconstruct this part of the mesh
  84899. _this.reconstructMesh(submeshIndex);
  84900. successCallback();
  84901. }, 0);
  84902. });
  84903. };
  84904. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84905. var _this = this;
  84906. this.vertices = [];
  84907. this.triangles = [];
  84908. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84909. var indices = this._mesh.getIndices();
  84910. var submesh = this._mesh.subMeshes[submeshIndex];
  84911. var findInVertices = function (positionToSearch) {
  84912. if (optimizeMesh) {
  84913. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84914. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84915. return _this.vertices[ii];
  84916. }
  84917. }
  84918. }
  84919. return null;
  84920. };
  84921. var vertexReferences = [];
  84922. var vertexInit = function (i) {
  84923. if (!positionData) {
  84924. return;
  84925. }
  84926. var offset = i + submesh.verticesStart;
  84927. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84928. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84929. vertex.originalOffsets.push(offset);
  84930. if (vertex.id === _this.vertices.length) {
  84931. _this.vertices.push(vertex);
  84932. }
  84933. vertexReferences.push(vertex.id);
  84934. };
  84935. //var totalVertices = mesh.getTotalVertices();
  84936. var totalVertices = submesh.verticesCount;
  84937. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84938. var indicesInit = function (i) {
  84939. if (!indices) {
  84940. return;
  84941. }
  84942. var offset = (submesh.indexStart / 3) + i;
  84943. var pos = (offset * 3);
  84944. var i0 = indices[pos + 0];
  84945. var i1 = indices[pos + 1];
  84946. var i2 = indices[pos + 2];
  84947. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84948. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84949. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84950. var triangle = new DecimationTriangle([v0, v1, v2]);
  84951. triangle.originalOffset = pos;
  84952. _this.triangles.push(triangle);
  84953. };
  84954. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84955. _this.init(callback);
  84956. });
  84957. });
  84958. };
  84959. QuadraticErrorSimplification.prototype.init = function (callback) {
  84960. var _this = this;
  84961. var triangleInit1 = function (i) {
  84962. var t = _this.triangles[i];
  84963. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84964. for (var j = 0; j < 3; j++) {
  84965. 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))));
  84966. }
  84967. };
  84968. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84969. var triangleInit2 = function (i) {
  84970. var t = _this.triangles[i];
  84971. for (var j = 0; j < 3; ++j) {
  84972. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84973. }
  84974. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84975. };
  84976. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84977. callback();
  84978. });
  84979. });
  84980. };
  84981. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84982. var newTriangles = [];
  84983. var i;
  84984. for (i = 0; i < this.vertices.length; ++i) {
  84985. this.vertices[i].triangleCount = 0;
  84986. }
  84987. var t;
  84988. var j;
  84989. for (i = 0; i < this.triangles.length; ++i) {
  84990. if (!this.triangles[i].deleted) {
  84991. t = this.triangles[i];
  84992. for (j = 0; j < 3; ++j) {
  84993. t.vertices[j].triangleCount = 1;
  84994. }
  84995. newTriangles.push(t);
  84996. }
  84997. }
  84998. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84999. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  85000. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  85001. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  85002. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  85003. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85004. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  85005. var vertexCount = 0;
  85006. for (i = 0; i < this.vertices.length; ++i) {
  85007. var vertex = this.vertices[i];
  85008. vertex.id = vertexCount;
  85009. if (vertex.triangleCount) {
  85010. vertex.originalOffsets.forEach(function (originalOffset) {
  85011. if (!normalData) {
  85012. return;
  85013. }
  85014. newPositionData.push(vertex.position.x);
  85015. newPositionData.push(vertex.position.y);
  85016. newPositionData.push(vertex.position.z);
  85017. newNormalData.push(normalData[originalOffset * 3]);
  85018. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  85019. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  85020. if (uvs && uvs.length) {
  85021. newUVsData.push(uvs[(originalOffset * 2)]);
  85022. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  85023. }
  85024. else if (colorsData && colorsData.length) {
  85025. newColorsData.push(colorsData[(originalOffset * 4)]);
  85026. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  85027. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  85028. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  85029. }
  85030. ++vertexCount;
  85031. });
  85032. }
  85033. }
  85034. var startingIndex = this._reconstructedMesh.getTotalIndices();
  85035. var startingVertex = this._reconstructedMesh.getTotalVertices();
  85036. var submeshesArray = this._reconstructedMesh.subMeshes;
  85037. this._reconstructedMesh.subMeshes = [];
  85038. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  85039. var originalIndices = this._mesh.getIndices();
  85040. for (i = 0; i < newTriangles.length; ++i) {
  85041. t = newTriangles[i]; //now get the new referencing point for each vertex
  85042. [0, 1, 2].forEach(function (idx) {
  85043. var id = originalIndices[t.originalOffset + idx];
  85044. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  85045. if (offset < 0)
  85046. offset = 0;
  85047. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  85048. });
  85049. }
  85050. //overwriting the old vertex buffers and indices.
  85051. this._reconstructedMesh.setIndices(newIndicesArray);
  85052. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  85053. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  85054. if (newUVsData.length > 0)
  85055. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  85056. if (newColorsData.length > 0)
  85057. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  85058. //create submesh
  85059. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  85060. if (submeshIndex > 0) {
  85061. this._reconstructedMesh.subMeshes = [];
  85062. submeshesArray.forEach(function (submesh) {
  85063. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  85064. });
  85065. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  85066. }
  85067. };
  85068. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  85069. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  85070. this._reconstructedMesh.material = this._mesh.material;
  85071. this._reconstructedMesh.parent = this._mesh.parent;
  85072. this._reconstructedMesh.isVisible = false;
  85073. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  85074. };
  85075. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  85076. for (var i = 0; i < vertex1.triangleCount; ++i) {
  85077. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  85078. if (t.deleted)
  85079. continue;
  85080. var s = this.references[vertex1.triangleStart + i].vertexId;
  85081. var v1 = t.vertices[(s + 1) % 3];
  85082. var v2 = t.vertices[(s + 2) % 3];
  85083. if ((v1 === vertex2 || v2 === vertex2)) {
  85084. deletedArray[i] = true;
  85085. delTr.push(t);
  85086. continue;
  85087. }
  85088. var d1 = v1.position.subtract(point);
  85089. d1 = d1.normalize();
  85090. var d2 = v2.position.subtract(point);
  85091. d2 = d2.normalize();
  85092. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  85093. return true;
  85094. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  85095. deletedArray[i] = false;
  85096. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  85097. return true;
  85098. }
  85099. return false;
  85100. };
  85101. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  85102. var newDeleted = deletedTriangles;
  85103. for (var i = 0; i < vertex.triangleCount; ++i) {
  85104. var ref = this.references[vertex.triangleStart + i];
  85105. var t = this.triangles[ref.triangleId];
  85106. if (t.deleted)
  85107. continue;
  85108. if (deletedArray[i] && t.deletePending) {
  85109. t.deleted = true;
  85110. newDeleted++;
  85111. continue;
  85112. }
  85113. t.vertices[ref.vertexId] = origVertex;
  85114. t.isDirty = true;
  85115. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  85116. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  85117. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  85118. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85119. this.references.push(ref);
  85120. }
  85121. return newDeleted;
  85122. };
  85123. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  85124. for (var i = 0; i < this.vertices.length; ++i) {
  85125. var vCount = [];
  85126. var vId = [];
  85127. var v = this.vertices[i];
  85128. var j;
  85129. for (j = 0; j < v.triangleCount; ++j) {
  85130. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  85131. for (var ii = 0; ii < 3; ii++) {
  85132. var ofs = 0;
  85133. var vv = triangle.vertices[ii];
  85134. while (ofs < vCount.length) {
  85135. if (vId[ofs] === vv.id)
  85136. break;
  85137. ++ofs;
  85138. }
  85139. if (ofs === vCount.length) {
  85140. vCount.push(1);
  85141. vId.push(vv.id);
  85142. }
  85143. else {
  85144. vCount[ofs]++;
  85145. }
  85146. }
  85147. }
  85148. for (j = 0; j < vCount.length; ++j) {
  85149. if (vCount[j] === 1) {
  85150. this.vertices[vId[j]].isBorder = true;
  85151. }
  85152. else {
  85153. this.vertices[vId[j]].isBorder = false;
  85154. }
  85155. }
  85156. }
  85157. };
  85158. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  85159. if (identifyBorders === void 0) { identifyBorders = false; }
  85160. var i;
  85161. if (!identifyBorders) {
  85162. var newTrianglesVector = [];
  85163. for (i = 0; i < this.triangles.length; ++i) {
  85164. if (!this.triangles[i].deleted) {
  85165. newTrianglesVector.push(this.triangles[i]);
  85166. }
  85167. }
  85168. this.triangles = newTrianglesVector;
  85169. }
  85170. for (i = 0; i < this.vertices.length; ++i) {
  85171. this.vertices[i].triangleCount = 0;
  85172. this.vertices[i].triangleStart = 0;
  85173. }
  85174. var t;
  85175. var j;
  85176. var v;
  85177. for (i = 0; i < this.triangles.length; ++i) {
  85178. t = this.triangles[i];
  85179. for (j = 0; j < 3; ++j) {
  85180. v = t.vertices[j];
  85181. v.triangleCount++;
  85182. }
  85183. }
  85184. var tStart = 0;
  85185. for (i = 0; i < this.vertices.length; ++i) {
  85186. this.vertices[i].triangleStart = tStart;
  85187. tStart += this.vertices[i].triangleCount;
  85188. this.vertices[i].triangleCount = 0;
  85189. }
  85190. var newReferences = new Array(this.triangles.length * 3);
  85191. for (i = 0; i < this.triangles.length; ++i) {
  85192. t = this.triangles[i];
  85193. for (j = 0; j < 3; ++j) {
  85194. v = t.vertices[j];
  85195. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  85196. v.triangleCount++;
  85197. }
  85198. }
  85199. this.references = newReferences;
  85200. if (identifyBorders) {
  85201. this.identifyBorder();
  85202. }
  85203. };
  85204. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  85205. var x = point.x;
  85206. var y = point.y;
  85207. var z = point.z;
  85208. 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
  85209. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  85210. };
  85211. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  85212. var q = vertex1.q.add(vertex2.q);
  85213. var border = vertex1.isBorder && vertex2.isBorder;
  85214. var error = 0;
  85215. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  85216. if (qDet !== 0 && !border) {
  85217. if (!pointResult) {
  85218. pointResult = BABYLON.Vector3.Zero();
  85219. }
  85220. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  85221. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  85222. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  85223. error = this.vertexError(q, pointResult);
  85224. }
  85225. else {
  85226. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  85227. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  85228. var error1 = this.vertexError(q, vertex1.position);
  85229. var error2 = this.vertexError(q, vertex2.position);
  85230. var error3 = this.vertexError(q, p3);
  85231. error = Math.min(error1, error2, error3);
  85232. if (error === error1) {
  85233. if (pointResult) {
  85234. pointResult.copyFrom(vertex1.position);
  85235. }
  85236. }
  85237. else if (error === error2) {
  85238. if (pointResult) {
  85239. pointResult.copyFrom(vertex2.position);
  85240. }
  85241. }
  85242. else {
  85243. if (pointResult) {
  85244. pointResult.copyFrom(p3);
  85245. }
  85246. }
  85247. }
  85248. return error;
  85249. };
  85250. return QuadraticErrorSimplification;
  85251. }());
  85252. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  85253. })(BABYLON || (BABYLON = {}));
  85254. //# sourceMappingURL=babylon.meshSimplification.js.map
  85255. "use strict";
  85256. var BABYLON;
  85257. (function (BABYLON) {
  85258. var MeshLODLevel = /** @class */ (function () {
  85259. function MeshLODLevel(distance, mesh) {
  85260. this.distance = distance;
  85261. this.mesh = mesh;
  85262. }
  85263. return MeshLODLevel;
  85264. }());
  85265. BABYLON.MeshLODLevel = MeshLODLevel;
  85266. })(BABYLON || (BABYLON = {}));
  85267. //# sourceMappingURL=babylon.meshLODLevel.js.map
  85268. "use strict";
  85269. var BABYLON;
  85270. (function (BABYLON) {
  85271. /**
  85272. * Defines the root class used to create scene optimization to use with SceneOptimizer
  85273. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85274. */
  85275. var SceneOptimization = /** @class */ (function () {
  85276. /**
  85277. * Creates the SceneOptimization object
  85278. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85279. * @param desc defines the description associated with the optimization
  85280. */
  85281. function SceneOptimization(
  85282. /**
  85283. * Defines the priority of this optimization (0 by default which means first in the list)
  85284. */
  85285. priority) {
  85286. if (priority === void 0) { priority = 0; }
  85287. this.priority = priority;
  85288. }
  85289. /**
  85290. * Gets a string describing the action executed by the current optimization
  85291. * @returns description string
  85292. */
  85293. SceneOptimization.prototype.getDescription = function () {
  85294. return "";
  85295. };
  85296. /**
  85297. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85298. * @param scene defines the current scene where to apply this optimization
  85299. * @param optimizer defines the current optimizer
  85300. * @returns true if everything that can be done was applied
  85301. */
  85302. SceneOptimization.prototype.apply = function (scene, optimizer) {
  85303. return true;
  85304. };
  85305. ;
  85306. return SceneOptimization;
  85307. }());
  85308. BABYLON.SceneOptimization = SceneOptimization;
  85309. /**
  85310. * Defines an optimization used to reduce the size of render target textures
  85311. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85312. */
  85313. var TextureOptimization = /** @class */ (function (_super) {
  85314. __extends(TextureOptimization, _super);
  85315. /**
  85316. * Creates the TextureOptimization object
  85317. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85318. * @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
  85319. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85320. */
  85321. function TextureOptimization(
  85322. /**
  85323. * Defines the priority of this optimization (0 by default which means first in the list)
  85324. */
  85325. priority,
  85326. /**
  85327. * 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
  85328. */
  85329. maximumSize,
  85330. /**
  85331. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85332. */
  85333. step) {
  85334. if (priority === void 0) { priority = 0; }
  85335. if (maximumSize === void 0) { maximumSize = 1024; }
  85336. if (step === void 0) { step = 0.5; }
  85337. var _this = _super.call(this, priority) || this;
  85338. _this.priority = priority;
  85339. _this.maximumSize = maximumSize;
  85340. _this.step = step;
  85341. return _this;
  85342. }
  85343. /**
  85344. * Gets a string describing the action executed by the current optimization
  85345. * @returns description string
  85346. */
  85347. TextureOptimization.prototype.getDescription = function () {
  85348. return "Reducing render target texture size to " + this.maximumSize;
  85349. };
  85350. /**
  85351. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85352. * @param scene defines the current scene where to apply this optimization
  85353. * @param optimizer defines the current optimizer
  85354. * @returns true if everything that can be done was applied
  85355. */
  85356. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85357. var allDone = true;
  85358. for (var index = 0; index < scene.textures.length; index++) {
  85359. var texture = scene.textures[index];
  85360. if (!texture.canRescale || texture.getContext) {
  85361. continue;
  85362. }
  85363. var currentSize = texture.getSize();
  85364. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85365. if (maxDimension > this.maximumSize) {
  85366. texture.scale(this.step);
  85367. allDone = false;
  85368. }
  85369. }
  85370. return allDone;
  85371. };
  85372. return TextureOptimization;
  85373. }(SceneOptimization));
  85374. BABYLON.TextureOptimization = TextureOptimization;
  85375. /**
  85376. * Defines an optimization used to increase or decrease the rendering resolution
  85377. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85378. */
  85379. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85380. __extends(HardwareScalingOptimization, _super);
  85381. /**
  85382. * Creates the HardwareScalingOptimization object
  85383. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85384. * @param maximumScale defines the maximum scale to use (2 by default)
  85385. * @param step defines the step to use between two passes (0.5 by default)
  85386. */
  85387. function HardwareScalingOptimization(
  85388. /**
  85389. * Defines the priority of this optimization (0 by default which means first in the list)
  85390. */
  85391. priority,
  85392. /**
  85393. * Defines the maximum scale to use (2 by default)
  85394. */
  85395. maximumScale,
  85396. /**
  85397. * Defines the step to use between two passes (0.5 by default)
  85398. */
  85399. step) {
  85400. if (priority === void 0) { priority = 0; }
  85401. if (maximumScale === void 0) { maximumScale = 2; }
  85402. if (step === void 0) { step = 0.25; }
  85403. var _this = _super.call(this, priority) || this;
  85404. _this.priority = priority;
  85405. _this.maximumScale = maximumScale;
  85406. _this.step = step;
  85407. _this._currentScale = -1;
  85408. _this._directionOffset = 1;
  85409. return _this;
  85410. }
  85411. /**
  85412. * Gets a string describing the action executed by the current optimization
  85413. * @return description string
  85414. */
  85415. HardwareScalingOptimization.prototype.getDescription = function () {
  85416. return "Setting hardware scaling level to " + this._currentScale;
  85417. };
  85418. /**
  85419. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85420. * @param scene defines the current scene where to apply this optimization
  85421. * @param optimizer defines the current optimizer
  85422. * @returns true if everything that can be done was applied
  85423. */
  85424. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85425. if (this._currentScale === -1) {
  85426. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85427. if (this._currentScale > this.maximumScale) {
  85428. this._directionOffset = -1;
  85429. }
  85430. }
  85431. this._currentScale += this._directionOffset * this.step;
  85432. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85433. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85434. };
  85435. ;
  85436. return HardwareScalingOptimization;
  85437. }(SceneOptimization));
  85438. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85439. /**
  85440. * Defines an optimization used to remove shadows
  85441. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85442. */
  85443. var ShadowsOptimization = /** @class */ (function (_super) {
  85444. __extends(ShadowsOptimization, _super);
  85445. function ShadowsOptimization() {
  85446. return _super !== null && _super.apply(this, arguments) || this;
  85447. }
  85448. /**
  85449. * Gets a string describing the action executed by the current optimization
  85450. * @return description string
  85451. */
  85452. ShadowsOptimization.prototype.getDescription = function () {
  85453. return "Turning shadows on/off";
  85454. };
  85455. /**
  85456. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85457. * @param scene defines the current scene where to apply this optimization
  85458. * @param optimizer defines the current optimizer
  85459. * @returns true if everything that can be done was applied
  85460. */
  85461. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85462. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85463. return true;
  85464. };
  85465. ;
  85466. return ShadowsOptimization;
  85467. }(SceneOptimization));
  85468. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85469. /**
  85470. * Defines an optimization used to turn post-processes off
  85471. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85472. */
  85473. var PostProcessesOptimization = /** @class */ (function (_super) {
  85474. __extends(PostProcessesOptimization, _super);
  85475. function PostProcessesOptimization() {
  85476. return _super !== null && _super.apply(this, arguments) || this;
  85477. }
  85478. /**
  85479. * Gets a string describing the action executed by the current optimization
  85480. * @return description string
  85481. */
  85482. PostProcessesOptimization.prototype.getDescription = function () {
  85483. return "Turning post-processes on/off";
  85484. };
  85485. /**
  85486. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85487. * @param scene defines the current scene where to apply this optimization
  85488. * @param optimizer defines the current optimizer
  85489. * @returns true if everything that can be done was applied
  85490. */
  85491. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85492. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85493. return true;
  85494. };
  85495. ;
  85496. return PostProcessesOptimization;
  85497. }(SceneOptimization));
  85498. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85499. /**
  85500. * Defines an optimization used to turn lens flares off
  85501. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85502. */
  85503. var LensFlaresOptimization = /** @class */ (function (_super) {
  85504. __extends(LensFlaresOptimization, _super);
  85505. function LensFlaresOptimization() {
  85506. return _super !== null && _super.apply(this, arguments) || this;
  85507. }
  85508. /**
  85509. * Gets a string describing the action executed by the current optimization
  85510. * @return description string
  85511. */
  85512. LensFlaresOptimization.prototype.getDescription = function () {
  85513. return "Turning lens flares on/off";
  85514. };
  85515. /**
  85516. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85517. * @param scene defines the current scene where to apply this optimization
  85518. * @param optimizer defines the current optimizer
  85519. * @returns true if everything that can be done was applied
  85520. */
  85521. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85522. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85523. return true;
  85524. };
  85525. ;
  85526. return LensFlaresOptimization;
  85527. }(SceneOptimization));
  85528. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85529. /**
  85530. * Defines an optimization based on user defined callback.
  85531. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85532. */
  85533. var CustomOptimization = /** @class */ (function (_super) {
  85534. __extends(CustomOptimization, _super);
  85535. function CustomOptimization() {
  85536. return _super !== null && _super.apply(this, arguments) || this;
  85537. }
  85538. /**
  85539. * Gets a string describing the action executed by the current optimization
  85540. * @returns description string
  85541. */
  85542. CustomOptimization.prototype.getDescription = function () {
  85543. if (this.onGetDescription) {
  85544. return this.onGetDescription();
  85545. }
  85546. return "Running user defined callback";
  85547. };
  85548. /**
  85549. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85550. * @param scene defines the current scene where to apply this optimization
  85551. * @param optimizer defines the current optimizer
  85552. * @returns true if everything that can be done was applied
  85553. */
  85554. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85555. if (this.onApply) {
  85556. return this.onApply(scene, optimizer);
  85557. }
  85558. return true;
  85559. };
  85560. ;
  85561. return CustomOptimization;
  85562. }(SceneOptimization));
  85563. BABYLON.CustomOptimization = CustomOptimization;
  85564. /**
  85565. * Defines an optimization used to turn particles off
  85566. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85567. */
  85568. var ParticlesOptimization = /** @class */ (function (_super) {
  85569. __extends(ParticlesOptimization, _super);
  85570. function ParticlesOptimization() {
  85571. return _super !== null && _super.apply(this, arguments) || this;
  85572. }
  85573. /**
  85574. * Gets a string describing the action executed by the current optimization
  85575. * @return description string
  85576. */
  85577. ParticlesOptimization.prototype.getDescription = function () {
  85578. return "Turning particles on/off";
  85579. };
  85580. /**
  85581. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85582. * @param scene defines the current scene where to apply this optimization
  85583. * @param optimizer defines the current optimizer
  85584. * @returns true if everything that can be done was applied
  85585. */
  85586. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85587. scene.particlesEnabled = optimizer.isInImprovementMode;
  85588. return true;
  85589. };
  85590. ;
  85591. return ParticlesOptimization;
  85592. }(SceneOptimization));
  85593. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85594. /**
  85595. * Defines an optimization used to turn render targets off
  85596. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85597. */
  85598. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85599. __extends(RenderTargetsOptimization, _super);
  85600. function RenderTargetsOptimization() {
  85601. return _super !== null && _super.apply(this, arguments) || this;
  85602. }
  85603. /**
  85604. * Gets a string describing the action executed by the current optimization
  85605. * @return description string
  85606. */
  85607. RenderTargetsOptimization.prototype.getDescription = function () {
  85608. return "Turning render targets off";
  85609. };
  85610. /**
  85611. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85612. * @param scene defines the current scene where to apply this optimization
  85613. * @param optimizer defines the current optimizer
  85614. * @returns true if everything that can be done was applied
  85615. */
  85616. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85617. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85618. return true;
  85619. };
  85620. ;
  85621. return RenderTargetsOptimization;
  85622. }(SceneOptimization));
  85623. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85624. /**
  85625. * Defines an optimization used to merge meshes with compatible materials
  85626. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85627. */
  85628. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85629. __extends(MergeMeshesOptimization, _super);
  85630. function MergeMeshesOptimization() {
  85631. var _this = _super !== null && _super.apply(this, arguments) || this;
  85632. _this._canBeMerged = function (abstractMesh) {
  85633. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85634. return false;
  85635. }
  85636. var mesh = abstractMesh;
  85637. if (!mesh.isVisible || !mesh.isEnabled()) {
  85638. return false;
  85639. }
  85640. if (mesh.instances.length > 0) {
  85641. return false;
  85642. }
  85643. if (mesh.skeleton || mesh.hasLODLevels) {
  85644. return false;
  85645. }
  85646. if (mesh.parent) {
  85647. return false;
  85648. }
  85649. return true;
  85650. };
  85651. return _this;
  85652. }
  85653. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85654. /**
  85655. * Gets or sets a boolean which defines if optimization octree has to be updated
  85656. */
  85657. get: function () {
  85658. return MergeMeshesOptimization._UpdateSelectionTree;
  85659. },
  85660. /**
  85661. * Gets or sets a boolean which defines if optimization octree has to be updated
  85662. */
  85663. set: function (value) {
  85664. MergeMeshesOptimization._UpdateSelectionTree = value;
  85665. },
  85666. enumerable: true,
  85667. configurable: true
  85668. });
  85669. /**
  85670. * Gets a string describing the action executed by the current optimization
  85671. * @return description string
  85672. */
  85673. MergeMeshesOptimization.prototype.getDescription = function () {
  85674. return "Merging similar meshes together";
  85675. };
  85676. /**
  85677. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85678. * @param scene defines the current scene where to apply this optimization
  85679. * @param optimizer defines the current optimizer
  85680. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85681. * @returns true if everything that can be done was applied
  85682. */
  85683. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85684. var globalPool = scene.meshes.slice(0);
  85685. var globalLength = globalPool.length;
  85686. for (var index = 0; index < globalLength; index++) {
  85687. var currentPool = new Array();
  85688. var current = globalPool[index];
  85689. // Checks
  85690. if (!this._canBeMerged(current)) {
  85691. continue;
  85692. }
  85693. currentPool.push(current);
  85694. // Find compatible meshes
  85695. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85696. var otherMesh = globalPool[subIndex];
  85697. if (!this._canBeMerged(otherMesh)) {
  85698. continue;
  85699. }
  85700. if (otherMesh.material !== current.material) {
  85701. continue;
  85702. }
  85703. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85704. continue;
  85705. }
  85706. currentPool.push(otherMesh);
  85707. globalLength--;
  85708. globalPool.splice(subIndex, 1);
  85709. subIndex--;
  85710. }
  85711. if (currentPool.length < 2) {
  85712. continue;
  85713. }
  85714. // Merge meshes
  85715. BABYLON.Mesh.MergeMeshes(currentPool);
  85716. }
  85717. if (updateSelectionTree != undefined) {
  85718. if (updateSelectionTree) {
  85719. scene.createOrUpdateSelectionOctree();
  85720. }
  85721. }
  85722. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85723. scene.createOrUpdateSelectionOctree();
  85724. }
  85725. return true;
  85726. };
  85727. ;
  85728. MergeMeshesOptimization._UpdateSelectionTree = false;
  85729. return MergeMeshesOptimization;
  85730. }(SceneOptimization));
  85731. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85732. /**
  85733. * Defines a list of options used by SceneOptimizer
  85734. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85735. */
  85736. var SceneOptimizerOptions = /** @class */ (function () {
  85737. /**
  85738. * Creates a new list of options used by SceneOptimizer
  85739. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85740. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85741. */
  85742. function SceneOptimizerOptions(
  85743. /**
  85744. * Defines the target frame rate to reach (60 by default)
  85745. */
  85746. targetFrameRate,
  85747. /**
  85748. * Defines the interval between two checkes (2000ms by default)
  85749. */
  85750. trackerDuration) {
  85751. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85752. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85753. this.targetFrameRate = targetFrameRate;
  85754. this.trackerDuration = trackerDuration;
  85755. /**
  85756. * Gets the list of optimizations to apply
  85757. */
  85758. this.optimizations = new Array();
  85759. }
  85760. /**
  85761. * Add a new optimization
  85762. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85763. * @returns the current SceneOptimizerOptions
  85764. */
  85765. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85766. this.optimizations.push(optimization);
  85767. return this;
  85768. };
  85769. /**
  85770. * Add a new custom optimization
  85771. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85772. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85773. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85774. * @returns the current SceneOptimizerOptions
  85775. */
  85776. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85777. if (priority === void 0) { priority = 0; }
  85778. var optimization = new CustomOptimization(priority);
  85779. optimization.onApply = onApply;
  85780. optimization.onGetDescription = onGetDescription;
  85781. this.optimizations.push(optimization);
  85782. return this;
  85783. };
  85784. /**
  85785. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85786. * @param targetFrameRate defines the target frame rate (60 by default)
  85787. * @returns a SceneOptimizerOptions object
  85788. */
  85789. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85790. var result = new SceneOptimizerOptions(targetFrameRate);
  85791. var priority = 0;
  85792. result.addOptimization(new MergeMeshesOptimization(priority));
  85793. result.addOptimization(new ShadowsOptimization(priority));
  85794. result.addOptimization(new LensFlaresOptimization(priority));
  85795. // Next priority
  85796. priority++;
  85797. result.addOptimization(new PostProcessesOptimization(priority));
  85798. result.addOptimization(new ParticlesOptimization(priority));
  85799. // Next priority
  85800. priority++;
  85801. result.addOptimization(new TextureOptimization(priority, 1024));
  85802. return result;
  85803. };
  85804. /**
  85805. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85806. * @param targetFrameRate defines the target frame rate (60 by default)
  85807. * @returns a SceneOptimizerOptions object
  85808. */
  85809. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85810. var result = new SceneOptimizerOptions(targetFrameRate);
  85811. var priority = 0;
  85812. result.addOptimization(new MergeMeshesOptimization(priority));
  85813. result.addOptimization(new ShadowsOptimization(priority));
  85814. result.addOptimization(new LensFlaresOptimization(priority));
  85815. // Next priority
  85816. priority++;
  85817. result.addOptimization(new PostProcessesOptimization(priority));
  85818. result.addOptimization(new ParticlesOptimization(priority));
  85819. // Next priority
  85820. priority++;
  85821. result.addOptimization(new TextureOptimization(priority, 512));
  85822. // Next priority
  85823. priority++;
  85824. result.addOptimization(new RenderTargetsOptimization(priority));
  85825. // Next priority
  85826. priority++;
  85827. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85828. return result;
  85829. };
  85830. /**
  85831. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85832. * @param targetFrameRate defines the target frame rate (60 by default)
  85833. * @returns a SceneOptimizerOptions object
  85834. */
  85835. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85836. var result = new SceneOptimizerOptions(targetFrameRate);
  85837. var priority = 0;
  85838. result.addOptimization(new MergeMeshesOptimization(priority));
  85839. result.addOptimization(new ShadowsOptimization(priority));
  85840. result.addOptimization(new LensFlaresOptimization(priority));
  85841. // Next priority
  85842. priority++;
  85843. result.addOptimization(new PostProcessesOptimization(priority));
  85844. result.addOptimization(new ParticlesOptimization(priority));
  85845. // Next priority
  85846. priority++;
  85847. result.addOptimization(new TextureOptimization(priority, 256));
  85848. // Next priority
  85849. priority++;
  85850. result.addOptimization(new RenderTargetsOptimization(priority));
  85851. // Next priority
  85852. priority++;
  85853. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85854. return result;
  85855. };
  85856. return SceneOptimizerOptions;
  85857. }());
  85858. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85859. /**
  85860. * Class used to run optimizations in order to reach a target frame rate
  85861. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85862. */
  85863. var SceneOptimizer = /** @class */ (function () {
  85864. /**
  85865. * Creates a new SceneOptimizer
  85866. * @param scene defines the scene to work on
  85867. * @param options defines the options to use with the SceneOptimizer
  85868. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85869. * @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)
  85870. */
  85871. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85872. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85873. if (improvementMode === void 0) { improvementMode = false; }
  85874. var _this = this;
  85875. this._isRunning = false;
  85876. this._currentPriorityLevel = 0;
  85877. this._targetFrameRate = 60;
  85878. this._trackerDuration = 2000;
  85879. this._currentFrameRate = 0;
  85880. this._improvementMode = false;
  85881. /**
  85882. * Defines an observable called when the optimizer reaches the target frame rate
  85883. */
  85884. this.onSuccessObservable = new BABYLON.Observable();
  85885. /**
  85886. * Defines an observable called when the optimizer enables an optimization
  85887. */
  85888. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85889. /**
  85890. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85891. */
  85892. this.onFailureObservable = new BABYLON.Observable();
  85893. if (!options) {
  85894. this._options = new SceneOptimizerOptions();
  85895. }
  85896. else {
  85897. this._options = options;
  85898. }
  85899. if (this._options.targetFrameRate) {
  85900. this._targetFrameRate = this._options.targetFrameRate;
  85901. }
  85902. if (this._options.trackerDuration) {
  85903. this._trackerDuration = this._options.trackerDuration;
  85904. }
  85905. if (autoGeneratePriorities) {
  85906. var priority = 0;
  85907. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85908. var optim = _a[_i];
  85909. optim.priority = priority++;
  85910. }
  85911. }
  85912. this._improvementMode = improvementMode;
  85913. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85914. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85915. _this._sceneDisposeObserver = null;
  85916. _this.dispose();
  85917. });
  85918. }
  85919. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85920. /**
  85921. * Gets a boolean indicating if the optimizer is in improvement mode
  85922. */
  85923. get: function () {
  85924. return this._improvementMode;
  85925. },
  85926. enumerable: true,
  85927. configurable: true
  85928. });
  85929. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85930. /**
  85931. * Gets the current priority level (0 at start)
  85932. */
  85933. get: function () {
  85934. return this._currentPriorityLevel;
  85935. },
  85936. enumerable: true,
  85937. configurable: true
  85938. });
  85939. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85940. /**
  85941. * Gets the current frame rate checked by the SceneOptimizer
  85942. */
  85943. get: function () {
  85944. return this._currentFrameRate;
  85945. },
  85946. enumerable: true,
  85947. configurable: true
  85948. });
  85949. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85950. /**
  85951. * Gets or sets the current target frame rate (60 by default)
  85952. */
  85953. get: function () {
  85954. return this._targetFrameRate;
  85955. },
  85956. /**
  85957. * Gets or sets the current target frame rate (60 by default)
  85958. */
  85959. set: function (value) {
  85960. this._targetFrameRate = value;
  85961. },
  85962. enumerable: true,
  85963. configurable: true
  85964. });
  85965. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85966. /**
  85967. * Gets or sets the current interval between two checks (every 2000ms by default)
  85968. */
  85969. get: function () {
  85970. return this._trackerDuration;
  85971. },
  85972. /**
  85973. * Gets or sets the current interval between two checks (every 2000ms by default)
  85974. */
  85975. set: function (value) {
  85976. this._trackerDuration = value;
  85977. },
  85978. enumerable: true,
  85979. configurable: true
  85980. });
  85981. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85982. /**
  85983. * Gets the list of active optimizations
  85984. */
  85985. get: function () {
  85986. return this._options.optimizations;
  85987. },
  85988. enumerable: true,
  85989. configurable: true
  85990. });
  85991. /**
  85992. * Stops the current optimizer
  85993. */
  85994. SceneOptimizer.prototype.stop = function () {
  85995. this._isRunning = false;
  85996. };
  85997. /**
  85998. * Reset the optimizer to initial step (current priority level = 0)
  85999. */
  86000. SceneOptimizer.prototype.reset = function () {
  86001. this._currentPriorityLevel = 0;
  86002. };
  86003. /**
  86004. * Start the optimizer. By default it will try to reach a specific framerate
  86005. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  86006. */
  86007. SceneOptimizer.prototype.start = function () {
  86008. var _this = this;
  86009. if (this._isRunning) {
  86010. return;
  86011. }
  86012. this._isRunning = true;
  86013. // Let's wait for the scene to be ready before running our check
  86014. this._scene.executeWhenReady(function () {
  86015. setTimeout(function () {
  86016. _this._checkCurrentState();
  86017. }, _this._trackerDuration);
  86018. });
  86019. };
  86020. SceneOptimizer.prototype._checkCurrentState = function () {
  86021. var _this = this;
  86022. if (!this._isRunning) {
  86023. return;
  86024. }
  86025. var scene = this._scene;
  86026. var options = this._options;
  86027. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  86028. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  86029. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  86030. this._isRunning = false;
  86031. this.onSuccessObservable.notifyObservers(this);
  86032. return;
  86033. }
  86034. // Apply current level of optimizations
  86035. var allDone = true;
  86036. var noOptimizationApplied = true;
  86037. for (var index = 0; index < options.optimizations.length; index++) {
  86038. var optimization = options.optimizations[index];
  86039. if (optimization.priority === this._currentPriorityLevel) {
  86040. noOptimizationApplied = false;
  86041. allDone = allDone && optimization.apply(scene, this);
  86042. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  86043. }
  86044. }
  86045. // If no optimization was applied, this is a failure :(
  86046. if (noOptimizationApplied) {
  86047. this._isRunning = false;
  86048. this.onFailureObservable.notifyObservers(this);
  86049. return;
  86050. }
  86051. // If all optimizations were done, move to next level
  86052. if (allDone) {
  86053. this._currentPriorityLevel++;
  86054. }
  86055. // Let's the system running for a specific amount of time before checking FPS
  86056. scene.executeWhenReady(function () {
  86057. setTimeout(function () {
  86058. _this._checkCurrentState();
  86059. }, _this._trackerDuration);
  86060. });
  86061. };
  86062. /**
  86063. * Release all resources
  86064. */
  86065. SceneOptimizer.prototype.dispose = function () {
  86066. this.stop();
  86067. this.onSuccessObservable.clear();
  86068. this.onFailureObservable.clear();
  86069. this.onNewOptimizationAppliedObservable.clear();
  86070. if (this._sceneDisposeObserver) {
  86071. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86072. }
  86073. };
  86074. /**
  86075. * Helper function to create a SceneOptimizer with one single line of code
  86076. * @param scene defines the scene to work on
  86077. * @param options defines the options to use with the SceneOptimizer
  86078. * @param onSuccess defines a callback to call on success
  86079. * @param onFailure defines a callback to call on failure
  86080. * @returns the new SceneOptimizer object
  86081. */
  86082. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  86083. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  86084. if (onSuccess) {
  86085. optimizer.onSuccessObservable.add(function () {
  86086. onSuccess();
  86087. });
  86088. }
  86089. if (onFailure) {
  86090. optimizer.onFailureObservable.add(function () {
  86091. onFailure();
  86092. });
  86093. }
  86094. optimizer.start();
  86095. return optimizer;
  86096. };
  86097. return SceneOptimizer;
  86098. }());
  86099. BABYLON.SceneOptimizer = SceneOptimizer;
  86100. })(BABYLON || (BABYLON = {}));
  86101. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  86102. "use strict";
  86103. var BABYLON;
  86104. (function (BABYLON) {
  86105. var OutlineRenderer = /** @class */ (function () {
  86106. function OutlineRenderer(scene) {
  86107. this.zOffset = 1;
  86108. this._scene = scene;
  86109. }
  86110. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  86111. var _this = this;
  86112. if (useOverlay === void 0) { useOverlay = false; }
  86113. var scene = this._scene;
  86114. var engine = this._scene.getEngine();
  86115. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86116. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  86117. return;
  86118. }
  86119. var mesh = subMesh.getRenderingMesh();
  86120. var material = subMesh.getMaterial();
  86121. if (!material || !scene.activeCamera) {
  86122. return;
  86123. }
  86124. engine.enableEffect(this._effect);
  86125. // Logarithmic depth
  86126. if (material.useLogarithmicDepth) {
  86127. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  86128. }
  86129. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  86130. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  86131. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  86132. // Bones
  86133. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86134. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86135. }
  86136. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  86137. // Alpha test
  86138. if (material && material.needAlphaTesting()) {
  86139. var alphaTexture = material.getAlphaTestTexture();
  86140. if (alphaTexture) {
  86141. this._effect.setTexture("diffuseSampler", alphaTexture);
  86142. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86143. }
  86144. }
  86145. engine.setZOffset(-this.zOffset);
  86146. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  86147. engine.setZOffset(0);
  86148. };
  86149. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  86150. var defines = [];
  86151. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  86152. var mesh = subMesh.getMesh();
  86153. var material = subMesh.getMaterial();
  86154. if (material) {
  86155. // Alpha test
  86156. if (material.needAlphaTesting()) {
  86157. defines.push("#define ALPHATEST");
  86158. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86159. attribs.push(BABYLON.VertexBuffer.UVKind);
  86160. defines.push("#define UV1");
  86161. }
  86162. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86163. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86164. defines.push("#define UV2");
  86165. }
  86166. }
  86167. //Logarithmic depth
  86168. if (material.useLogarithmicDepth) {
  86169. defines.push("#define LOGARITHMICDEPTH");
  86170. }
  86171. }
  86172. // Bones
  86173. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86174. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86175. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86176. if (mesh.numBoneInfluencers > 4) {
  86177. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86178. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86179. }
  86180. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86181. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  86182. }
  86183. else {
  86184. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86185. }
  86186. // Instances
  86187. if (useInstances) {
  86188. defines.push("#define INSTANCES");
  86189. attribs.push("world0");
  86190. attribs.push("world1");
  86191. attribs.push("world2");
  86192. attribs.push("world3");
  86193. }
  86194. // Get correct effect
  86195. var join = defines.join("\n");
  86196. if (this._cachedDefines !== join) {
  86197. this._cachedDefines = join;
  86198. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  86199. }
  86200. return this._effect.isReady();
  86201. };
  86202. return OutlineRenderer;
  86203. }());
  86204. BABYLON.OutlineRenderer = OutlineRenderer;
  86205. })(BABYLON || (BABYLON = {}));
  86206. //# sourceMappingURL=babylon.outlineRenderer.js.map
  86207. "use strict";
  86208. var BABYLON;
  86209. (function (BABYLON) {
  86210. var FaceAdjacencies = /** @class */ (function () {
  86211. function FaceAdjacencies() {
  86212. this.edges = new Array();
  86213. this.edgesConnectedCount = 0;
  86214. }
  86215. return FaceAdjacencies;
  86216. }());
  86217. var EdgesRenderer = /** @class */ (function () {
  86218. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  86219. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  86220. if (epsilon === void 0) { epsilon = 0.95; }
  86221. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  86222. this.edgesWidthScalerForOrthographic = 1000.0;
  86223. this.edgesWidthScalerForPerspective = 50.0;
  86224. this._linesPositions = new Array();
  86225. this._linesNormals = new Array();
  86226. this._linesIndices = new Array();
  86227. this._buffers = {};
  86228. this._checkVerticesInsteadOfIndices = false;
  86229. this._source = source;
  86230. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  86231. this._epsilon = epsilon;
  86232. this._prepareRessources();
  86233. this._generateEdgesLines();
  86234. }
  86235. EdgesRenderer.prototype._prepareRessources = function () {
  86236. if (this._lineShader) {
  86237. return;
  86238. }
  86239. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  86240. attributes: ["position", "normal"],
  86241. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  86242. });
  86243. this._lineShader.disableDepthWrite = true;
  86244. this._lineShader.backFaceCulling = false;
  86245. };
  86246. EdgesRenderer.prototype._rebuild = function () {
  86247. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86248. if (buffer) {
  86249. buffer._rebuild();
  86250. }
  86251. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86252. if (buffer) {
  86253. buffer._rebuild();
  86254. }
  86255. var scene = this._source.getScene();
  86256. var engine = scene.getEngine();
  86257. this._ib = engine.createIndexBuffer(this._linesIndices);
  86258. };
  86259. EdgesRenderer.prototype.dispose = function () {
  86260. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86261. if (buffer) {
  86262. buffer.dispose();
  86263. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  86264. }
  86265. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86266. if (buffer) {
  86267. buffer.dispose();
  86268. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  86269. }
  86270. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  86271. this._lineShader.dispose();
  86272. };
  86273. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  86274. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  86275. return 0;
  86276. }
  86277. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  86278. return 1;
  86279. }
  86280. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  86281. return 2;
  86282. }
  86283. return -1;
  86284. };
  86285. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  86286. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  86287. return 0;
  86288. }
  86289. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  86290. return 1;
  86291. }
  86292. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  86293. return 2;
  86294. }
  86295. return -1;
  86296. };
  86297. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  86298. var needToCreateLine;
  86299. if (edge === undefined) {
  86300. needToCreateLine = true;
  86301. }
  86302. else {
  86303. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  86304. needToCreateLine = dotProduct < this._epsilon;
  86305. }
  86306. if (needToCreateLine) {
  86307. var offset = this._linesPositions.length / 3;
  86308. var normal = p0.subtract(p1);
  86309. normal.normalize();
  86310. // Positions
  86311. this._linesPositions.push(p0.x);
  86312. this._linesPositions.push(p0.y);
  86313. this._linesPositions.push(p0.z);
  86314. this._linesPositions.push(p0.x);
  86315. this._linesPositions.push(p0.y);
  86316. this._linesPositions.push(p0.z);
  86317. this._linesPositions.push(p1.x);
  86318. this._linesPositions.push(p1.y);
  86319. this._linesPositions.push(p1.z);
  86320. this._linesPositions.push(p1.x);
  86321. this._linesPositions.push(p1.y);
  86322. this._linesPositions.push(p1.z);
  86323. // Normals
  86324. this._linesNormals.push(p1.x);
  86325. this._linesNormals.push(p1.y);
  86326. this._linesNormals.push(p1.z);
  86327. this._linesNormals.push(-1);
  86328. this._linesNormals.push(p1.x);
  86329. this._linesNormals.push(p1.y);
  86330. this._linesNormals.push(p1.z);
  86331. this._linesNormals.push(1);
  86332. this._linesNormals.push(p0.x);
  86333. this._linesNormals.push(p0.y);
  86334. this._linesNormals.push(p0.z);
  86335. this._linesNormals.push(-1);
  86336. this._linesNormals.push(p0.x);
  86337. this._linesNormals.push(p0.y);
  86338. this._linesNormals.push(p0.z);
  86339. this._linesNormals.push(1);
  86340. // Indices
  86341. this._linesIndices.push(offset);
  86342. this._linesIndices.push(offset + 1);
  86343. this._linesIndices.push(offset + 2);
  86344. this._linesIndices.push(offset);
  86345. this._linesIndices.push(offset + 2);
  86346. this._linesIndices.push(offset + 3);
  86347. }
  86348. };
  86349. EdgesRenderer.prototype._generateEdgesLines = function () {
  86350. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86351. var indices = this._source.getIndices();
  86352. if (!indices || !positions) {
  86353. return;
  86354. }
  86355. // First let's find adjacencies
  86356. var adjacencies = new Array();
  86357. var faceNormals = new Array();
  86358. var index;
  86359. var faceAdjacencies;
  86360. // Prepare faces
  86361. for (index = 0; index < indices.length; index += 3) {
  86362. faceAdjacencies = new FaceAdjacencies();
  86363. var p0Index = indices[index];
  86364. var p1Index = indices[index + 1];
  86365. var p2Index = indices[index + 2];
  86366. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86367. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86368. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86369. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86370. faceNormal.normalize();
  86371. faceNormals.push(faceNormal);
  86372. adjacencies.push(faceAdjacencies);
  86373. }
  86374. // Scan
  86375. for (index = 0; index < adjacencies.length; index++) {
  86376. faceAdjacencies = adjacencies[index];
  86377. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86378. var otherFaceAdjacencies = adjacencies[otherIndex];
  86379. if (faceAdjacencies.edgesConnectedCount === 3) {
  86380. break;
  86381. }
  86382. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86383. continue;
  86384. }
  86385. var otherP0 = indices[otherIndex * 3];
  86386. var otherP1 = indices[otherIndex * 3 + 1];
  86387. var otherP2 = indices[otherIndex * 3 + 2];
  86388. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86389. var otherEdgeIndex = 0;
  86390. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86391. continue;
  86392. }
  86393. switch (edgeIndex) {
  86394. case 0:
  86395. if (this._checkVerticesInsteadOfIndices) {
  86396. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86397. }
  86398. else {
  86399. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86400. }
  86401. break;
  86402. case 1:
  86403. if (this._checkVerticesInsteadOfIndices) {
  86404. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86405. }
  86406. else {
  86407. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86408. }
  86409. break;
  86410. case 2:
  86411. if (this._checkVerticesInsteadOfIndices) {
  86412. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86413. }
  86414. else {
  86415. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86416. }
  86417. break;
  86418. }
  86419. if (otherEdgeIndex === -1) {
  86420. continue;
  86421. }
  86422. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86423. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86424. faceAdjacencies.edgesConnectedCount++;
  86425. otherFaceAdjacencies.edgesConnectedCount++;
  86426. if (faceAdjacencies.edgesConnectedCount === 3) {
  86427. break;
  86428. }
  86429. }
  86430. }
  86431. }
  86432. // Create lines
  86433. for (index = 0; index < adjacencies.length; index++) {
  86434. // 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
  86435. var current = adjacencies[index];
  86436. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86437. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86438. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86439. }
  86440. // Merge into a single mesh
  86441. var engine = this._source.getScene().getEngine();
  86442. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86443. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86444. this._ib = engine.createIndexBuffer(this._linesIndices);
  86445. this._indicesCount = this._linesIndices.length;
  86446. };
  86447. EdgesRenderer.prototype.render = function () {
  86448. var scene = this._source.getScene();
  86449. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86450. return;
  86451. }
  86452. var engine = scene.getEngine();
  86453. this._lineShader._preBind();
  86454. // VBOs
  86455. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86456. scene.resetCachedMaterial();
  86457. this._lineShader.setColor4("color", this._source.edgesColor);
  86458. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86459. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86460. }
  86461. else {
  86462. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86463. }
  86464. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86465. this._lineShader.bind(this._source.getWorldMatrix());
  86466. // Draw order
  86467. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86468. this._lineShader.unbind();
  86469. engine.setDepthWrite(true);
  86470. };
  86471. return EdgesRenderer;
  86472. }());
  86473. BABYLON.EdgesRenderer = EdgesRenderer;
  86474. })(BABYLON || (BABYLON = {}));
  86475. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86476. "use strict";
  86477. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86478. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86479. s = arguments[i];
  86480. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86481. t[p] = s[p];
  86482. }
  86483. return t;
  86484. };
  86485. var BABYLON;
  86486. (function (BABYLON) {
  86487. /**
  86488. * The effect layer Helps adding post process effect blended with the main pass.
  86489. *
  86490. * This can be for instance use to generate glow or higlight effects on the scene.
  86491. *
  86492. * The effect layer class can not be used directly and is intented to inherited from to be
  86493. * customized per effects.
  86494. */
  86495. var EffectLayer = /** @class */ (function () {
  86496. /**
  86497. * Instantiates a new effect Layer and references it in the scene.
  86498. * @param name The name of the layer
  86499. * @param scene The scene to use the layer in
  86500. */
  86501. function EffectLayer(
  86502. /** The Friendly of the effect in the scene */
  86503. name, scene) {
  86504. this.name = name;
  86505. this._vertexBuffers = {};
  86506. this._maxSize = 0;
  86507. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86508. this._shouldRender = true;
  86509. this._postProcesses = [];
  86510. this._textures = [];
  86511. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86512. /**
  86513. * The clear color of the texture used to generate the glow map.
  86514. */
  86515. this.neutralColor = new BABYLON.Color4();
  86516. /**
  86517. * Specifies wether the highlight layer is enabled or not.
  86518. */
  86519. this.isEnabled = true;
  86520. /**
  86521. * An event triggered when the effect layer has been disposed.
  86522. */
  86523. this.onDisposeObservable = new BABYLON.Observable();
  86524. /**
  86525. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86526. */
  86527. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86528. /**
  86529. * An event triggered when the generated texture is being merged in the scene.
  86530. */
  86531. this.onBeforeComposeObservable = new BABYLON.Observable();
  86532. /**
  86533. * An event triggered when the generated texture has been merged in the scene.
  86534. */
  86535. this.onAfterComposeObservable = new BABYLON.Observable();
  86536. /**
  86537. * An event triggered when the efffect layer changes its size.
  86538. */
  86539. this.onSizeChangedObservable = new BABYLON.Observable();
  86540. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86541. this._engine = scene.getEngine();
  86542. this._maxSize = this._engine.getCaps().maxTextureSize;
  86543. this._scene.effectLayers.push(this);
  86544. // Generate Buffers
  86545. this._generateIndexBuffer();
  86546. this._genrateVertexBuffer();
  86547. }
  86548. Object.defineProperty(EffectLayer.prototype, "camera", {
  86549. /**
  86550. * Gets the camera attached to the layer.
  86551. */
  86552. get: function () {
  86553. return this._effectLayerOptions.camera;
  86554. },
  86555. enumerable: true,
  86556. configurable: true
  86557. });
  86558. /**
  86559. * Initializes the effect layer with the required options.
  86560. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86561. */
  86562. EffectLayer.prototype._init = function (options) {
  86563. // Adapt options
  86564. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86565. this._setMainTextureSize();
  86566. this._createMainTexture();
  86567. this._createTextureAndPostProcesses();
  86568. this._mergeEffect = this._createMergeEffect();
  86569. };
  86570. /**
  86571. * Generates the index buffer of the full screen quad blending to the main canvas.
  86572. */
  86573. EffectLayer.prototype._generateIndexBuffer = function () {
  86574. // Indices
  86575. var indices = [];
  86576. indices.push(0);
  86577. indices.push(1);
  86578. indices.push(2);
  86579. indices.push(0);
  86580. indices.push(2);
  86581. indices.push(3);
  86582. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86583. };
  86584. /**
  86585. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86586. */
  86587. EffectLayer.prototype._genrateVertexBuffer = function () {
  86588. // VBO
  86589. var vertices = [];
  86590. vertices.push(1, 1);
  86591. vertices.push(-1, 1);
  86592. vertices.push(-1, -1);
  86593. vertices.push(1, -1);
  86594. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86595. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86596. };
  86597. /**
  86598. * Sets the main texture desired size which is the closest power of two
  86599. * of the engine canvas size.
  86600. */
  86601. EffectLayer.prototype._setMainTextureSize = function () {
  86602. if (this._effectLayerOptions.mainTextureFixedSize) {
  86603. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86604. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86605. }
  86606. else {
  86607. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86608. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86609. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86610. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86611. }
  86612. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86613. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86614. };
  86615. /**
  86616. * Creates the main texture for the effect layer.
  86617. */
  86618. EffectLayer.prototype._createMainTexture = function () {
  86619. var _this = this;
  86620. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86621. width: this._mainTextureDesiredSize.width,
  86622. height: this._mainTextureDesiredSize.height
  86623. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86624. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86625. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86626. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86627. this._mainTexture.anisotropicFilteringLevel = 1;
  86628. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86629. this._mainTexture.renderParticles = false;
  86630. this._mainTexture.renderList = null;
  86631. this._mainTexture.ignoreCameraViewport = true;
  86632. // Custom render function
  86633. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86634. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86635. var index;
  86636. var engine = _this._scene.getEngine();
  86637. if (depthOnlySubMeshes.length) {
  86638. engine.setColorWrite(false);
  86639. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86640. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86641. }
  86642. engine.setColorWrite(true);
  86643. }
  86644. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86645. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86646. }
  86647. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86648. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86649. }
  86650. for (index = 0; index < transparentSubMeshes.length; index++) {
  86651. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86652. }
  86653. };
  86654. this._mainTexture.onClearObservable.add(function (engine) {
  86655. engine.clear(_this.neutralColor, true, true, true);
  86656. });
  86657. };
  86658. /**
  86659. * Checks for the readiness of the element composing the layer.
  86660. * @param subMesh the mesh to check for
  86661. * @param useInstances specify wether or not to use instances to render the mesh
  86662. * @param emissiveTexture the associated emissive texture used to generate the glow
  86663. * @return true if ready otherwise, false
  86664. */
  86665. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86666. var material = subMesh.getMaterial();
  86667. if (!material) {
  86668. return false;
  86669. }
  86670. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86671. return false;
  86672. }
  86673. var defines = [];
  86674. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86675. var mesh = subMesh.getMesh();
  86676. var uv1 = false;
  86677. var uv2 = false;
  86678. // Alpha test
  86679. if (material && material.needAlphaTesting()) {
  86680. var alphaTexture = material.getAlphaTestTexture();
  86681. if (alphaTexture) {
  86682. defines.push("#define ALPHATEST");
  86683. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86684. alphaTexture.coordinatesIndex === 1) {
  86685. defines.push("#define DIFFUSEUV2");
  86686. uv2 = true;
  86687. }
  86688. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86689. defines.push("#define DIFFUSEUV1");
  86690. uv1 = true;
  86691. }
  86692. }
  86693. }
  86694. // Emissive
  86695. if (emissiveTexture) {
  86696. defines.push("#define EMISSIVE");
  86697. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86698. emissiveTexture.coordinatesIndex === 1) {
  86699. defines.push("#define EMISSIVEUV2");
  86700. uv2 = true;
  86701. }
  86702. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86703. defines.push("#define EMISSIVEUV1");
  86704. uv1 = true;
  86705. }
  86706. }
  86707. if (uv1) {
  86708. attribs.push(BABYLON.VertexBuffer.UVKind);
  86709. defines.push("#define UV1");
  86710. }
  86711. if (uv2) {
  86712. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86713. defines.push("#define UV2");
  86714. }
  86715. // Bones
  86716. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86717. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86718. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86719. if (mesh.numBoneInfluencers > 4) {
  86720. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86721. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86722. }
  86723. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86724. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86725. }
  86726. else {
  86727. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86728. }
  86729. // Morph targets
  86730. var manager = mesh.morphTargetManager;
  86731. var morphInfluencers = 0;
  86732. if (manager) {
  86733. if (manager.numInfluencers > 0) {
  86734. defines.push("#define MORPHTARGETS");
  86735. morphInfluencers = manager.numInfluencers;
  86736. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  86737. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  86738. }
  86739. }
  86740. // Instances
  86741. if (useInstances) {
  86742. defines.push("#define INSTANCES");
  86743. attribs.push("world0");
  86744. attribs.push("world1");
  86745. attribs.push("world2");
  86746. attribs.push("world3");
  86747. }
  86748. // Get correct effect
  86749. var join = defines.join("\n");
  86750. if (this._cachedDefines !== join) {
  86751. this._cachedDefines = join;
  86752. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  86753. }
  86754. return this._effectLayerMapGenerationEffect.isReady();
  86755. };
  86756. /**
  86757. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86758. */
  86759. EffectLayer.prototype.render = function () {
  86760. var currentEffect = this._mergeEffect;
  86761. // Check
  86762. if (!currentEffect.isReady())
  86763. return;
  86764. for (var i = 0; i < this._postProcesses.length; i++) {
  86765. if (!this._postProcesses[i].isReady()) {
  86766. return;
  86767. }
  86768. }
  86769. var engine = this._scene.getEngine();
  86770. this.onBeforeComposeObservable.notifyObservers(this);
  86771. // Render
  86772. engine.enableEffect(currentEffect);
  86773. engine.setState(false);
  86774. // VBOs
  86775. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86776. // Cache
  86777. var previousAlphaMode = engine.getAlphaMode();
  86778. // Go Blend.
  86779. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86780. // Blends the map on the main canvas.
  86781. this._internalRender(currentEffect);
  86782. // Restore Alpha
  86783. engine.setAlphaMode(previousAlphaMode);
  86784. this.onAfterComposeObservable.notifyObservers(this);
  86785. // Handle size changes.
  86786. var size = this._mainTexture.getSize();
  86787. this._setMainTextureSize();
  86788. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86789. // Recreate RTT and post processes on size change.
  86790. this.onSizeChangedObservable.notifyObservers(this);
  86791. this._disposeTextureAndPostProcesses();
  86792. this._createMainTexture();
  86793. this._createTextureAndPostProcesses();
  86794. }
  86795. };
  86796. /**
  86797. * Determine if a given mesh will be used in the current effect.
  86798. * @param mesh mesh to test
  86799. * @returns true if the mesh will be used
  86800. */
  86801. EffectLayer.prototype.hasMesh = function (mesh) {
  86802. return true;
  86803. };
  86804. /**
  86805. * Returns true if the layer contains information to display, otherwise false.
  86806. * @returns true if the glow layer should be rendered
  86807. */
  86808. EffectLayer.prototype.shouldRender = function () {
  86809. return this.isEnabled && this._shouldRender;
  86810. };
  86811. /**
  86812. * Returns true if the mesh should render, otherwise false.
  86813. * @param mesh The mesh to render
  86814. * @returns true if it should render otherwise false
  86815. */
  86816. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86817. return true;
  86818. };
  86819. /**
  86820. * Returns true if the mesh should render, otherwise false.
  86821. * @param mesh The mesh to render
  86822. * @returns true if it should render otherwise false
  86823. */
  86824. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86825. return true;
  86826. };
  86827. /**
  86828. * Renders the submesh passed in parameter to the generation map.
  86829. */
  86830. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86831. var _this = this;
  86832. if (!this.shouldRender()) {
  86833. return;
  86834. }
  86835. var material = subMesh.getMaterial();
  86836. var mesh = subMesh.getRenderingMesh();
  86837. var scene = this._scene;
  86838. var engine = scene.getEngine();
  86839. if (!material) {
  86840. return;
  86841. }
  86842. // Do not block in blend mode.
  86843. if (material.needAlphaBlendingForMesh(mesh)) {
  86844. return;
  86845. }
  86846. // Culling
  86847. engine.setState(material.backFaceCulling);
  86848. // Managing instances
  86849. var batch = mesh._getInstancesRenderList(subMesh._id);
  86850. if (batch.mustReturn) {
  86851. return;
  86852. }
  86853. // Early Exit per mesh
  86854. if (!this._shouldRenderMesh(mesh)) {
  86855. return;
  86856. }
  86857. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86858. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86859. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86860. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86861. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86862. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86863. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86864. // Alpha test
  86865. if (material && material.needAlphaTesting()) {
  86866. var alphaTexture = material.getAlphaTestTexture();
  86867. if (alphaTexture) {
  86868. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86869. var textureMatrix = alphaTexture.getTextureMatrix();
  86870. if (textureMatrix) {
  86871. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86872. }
  86873. }
  86874. }
  86875. // Glow emissive only
  86876. if (this._emissiveTextureAndColor.texture) {
  86877. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86878. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86879. }
  86880. // Bones
  86881. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86882. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86883. }
  86884. // Morph targets
  86885. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  86886. // Draw
  86887. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86888. }
  86889. else {
  86890. // Need to reset refresh rate of the shadowMap
  86891. this._mainTexture.resetRefreshCounter();
  86892. }
  86893. };
  86894. /**
  86895. * Rebuild the required buffers.
  86896. * @ignore Internal use only.
  86897. */
  86898. EffectLayer.prototype._rebuild = function () {
  86899. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86900. if (vb) {
  86901. vb._rebuild();
  86902. }
  86903. this._generateIndexBuffer();
  86904. };
  86905. /**
  86906. * Dispose only the render target textures and post process.
  86907. */
  86908. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86909. this._mainTexture.dispose();
  86910. for (var i = 0; i < this._postProcesses.length; i++) {
  86911. if (this._postProcesses[i]) {
  86912. this._postProcesses[i].dispose();
  86913. }
  86914. }
  86915. this._postProcesses = [];
  86916. for (var i = 0; i < this._textures.length; i++) {
  86917. if (this._textures[i]) {
  86918. this._textures[i].dispose();
  86919. }
  86920. }
  86921. this._textures = [];
  86922. };
  86923. /**
  86924. * Dispose the highlight layer and free resources.
  86925. */
  86926. EffectLayer.prototype.dispose = function () {
  86927. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86928. if (vertexBuffer) {
  86929. vertexBuffer.dispose();
  86930. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86931. }
  86932. if (this._indexBuffer) {
  86933. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86934. this._indexBuffer = null;
  86935. }
  86936. // Clean textures and post processes
  86937. this._disposeTextureAndPostProcesses();
  86938. // Remove from scene
  86939. var index = this._scene.effectLayers.indexOf(this, 0);
  86940. if (index > -1) {
  86941. this._scene.effectLayers.splice(index, 1);
  86942. }
  86943. // Callback
  86944. this.onDisposeObservable.notifyObservers(this);
  86945. this.onDisposeObservable.clear();
  86946. this.onBeforeRenderMainTextureObservable.clear();
  86947. this.onBeforeComposeObservable.clear();
  86948. this.onAfterComposeObservable.clear();
  86949. this.onSizeChangedObservable.clear();
  86950. };
  86951. return EffectLayer;
  86952. }());
  86953. BABYLON.EffectLayer = EffectLayer;
  86954. })(BABYLON || (BABYLON = {}));
  86955. //# sourceMappingURL=babylon.effectLayer.js.map
  86956. "use strict";
  86957. var BABYLON;
  86958. (function (BABYLON) {
  86959. /**
  86960. * Special Glow Blur post process only blurring the alpha channel
  86961. * It enforces keeping the most luminous color in the color channel.
  86962. */
  86963. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86964. __extends(GlowBlurPostProcess, _super);
  86965. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86966. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86967. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86968. _this.direction = direction;
  86969. _this.kernel = kernel;
  86970. _this.onApplyObservable.add(function (effect) {
  86971. effect.setFloat2("screenSize", _this.width, _this.height);
  86972. effect.setVector2("direction", _this.direction);
  86973. effect.setFloat("blurWidth", _this.kernel);
  86974. });
  86975. return _this;
  86976. }
  86977. return GlowBlurPostProcess;
  86978. }(BABYLON.PostProcess));
  86979. /**
  86980. * The highlight layer Helps adding a glow effect around a mesh.
  86981. *
  86982. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86983. * glowy meshes to your scene.
  86984. *
  86985. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86986. */
  86987. var HighlightLayer = /** @class */ (function (_super) {
  86988. __extends(HighlightLayer, _super);
  86989. /**
  86990. * Instantiates a new highlight Layer and references it to the scene..
  86991. * @param name The name of the layer
  86992. * @param scene The scene to use the layer in
  86993. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86994. */
  86995. function HighlightLayer(name, scene, options) {
  86996. var _this = _super.call(this, name, scene) || this;
  86997. _this.name = name;
  86998. /**
  86999. * Specifies whether or not the inner glow is ACTIVE in the layer.
  87000. */
  87001. _this.innerGlow = true;
  87002. /**
  87003. * Specifies whether or not the outer glow is ACTIVE in the layer.
  87004. */
  87005. _this.outerGlow = true;
  87006. /**
  87007. * An event triggered when the highlight layer is being blurred.
  87008. */
  87009. _this.onBeforeBlurObservable = new BABYLON.Observable();
  87010. /**
  87011. * An event triggered when the highlight layer has been blurred.
  87012. */
  87013. _this.onAfterBlurObservable = new BABYLON.Observable();
  87014. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  87015. _this._meshes = {};
  87016. _this._excludedMeshes = {};
  87017. _this.neutralColor = HighlightLayer.NeutralColor;
  87018. // Warn on stencil
  87019. if (!_this._engine.isStencilEnable) {
  87020. 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 }");
  87021. }
  87022. // Adapt options
  87023. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  87024. // Initialize the layer
  87025. _this._init({
  87026. alphaBlendingMode: _this._options.alphaBlendingMode,
  87027. camera: _this._options.camera,
  87028. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87029. mainTextureRatio: _this._options.mainTextureRatio
  87030. });
  87031. // Do not render as long as no meshes have been added
  87032. _this._shouldRender = false;
  87033. return _this;
  87034. }
  87035. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  87036. /**
  87037. * Gets the horizontal size of the blur.
  87038. */
  87039. get: function () {
  87040. return this._horizontalBlurPostprocess.kernel;
  87041. },
  87042. /**
  87043. * Specifies the horizontal size of the blur.
  87044. */
  87045. set: function (value) {
  87046. this._horizontalBlurPostprocess.kernel = value;
  87047. },
  87048. enumerable: true,
  87049. configurable: true
  87050. });
  87051. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  87052. /**
  87053. * Gets the vertical size of the blur.
  87054. */
  87055. get: function () {
  87056. return this._verticalBlurPostprocess.kernel;
  87057. },
  87058. /**
  87059. * Specifies the vertical size of the blur.
  87060. */
  87061. set: function (value) {
  87062. this._verticalBlurPostprocess.kernel = value;
  87063. },
  87064. enumerable: true,
  87065. configurable: true
  87066. });
  87067. /**
  87068. * Get the effect name of the layer.
  87069. * @return The effect name
  87070. */
  87071. HighlightLayer.prototype.getEffectName = function () {
  87072. return HighlightLayer.EffectName;
  87073. };
  87074. /**
  87075. * Create the merge effect. This is the shader use to blit the information back
  87076. * to the main canvas at the end of the scene rendering.
  87077. */
  87078. HighlightLayer.prototype._createMergeEffect = function () {
  87079. // Effect
  87080. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  87081. };
  87082. /**
  87083. * Creates the render target textures and post processes used in the highlight layer.
  87084. */
  87085. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  87086. var _this = this;
  87087. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  87088. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  87089. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87090. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87091. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  87092. width: blurTextureWidth,
  87093. height: blurTextureHeight
  87094. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87095. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87096. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87097. this._blurTexture.anisotropicFilteringLevel = 16;
  87098. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  87099. this._blurTexture.renderParticles = false;
  87100. this._blurTexture.ignoreCameraViewport = true;
  87101. this._textures = [this._blurTexture];
  87102. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  87103. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87104. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  87105. effect.setTexture("textureSampler", _this._mainTexture);
  87106. });
  87107. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87108. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87109. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87110. });
  87111. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87112. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  87113. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87114. });
  87115. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87116. }
  87117. else {
  87118. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  87119. width: blurTextureWidth,
  87120. height: blurTextureHeight
  87121. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87122. this._horizontalBlurPostprocess.width = blurTextureWidth;
  87123. this._horizontalBlurPostprocess.height = blurTextureHeight;
  87124. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87125. effect.setTexture("textureSampler", _this._mainTexture);
  87126. });
  87127. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  87128. width: blurTextureWidth,
  87129. height: blurTextureHeight
  87130. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87131. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87132. }
  87133. this._mainTexture.onAfterUnbindObservable.add(function () {
  87134. _this.onBeforeBlurObservable.notifyObservers(_this);
  87135. var internalTexture = _this._blurTexture.getInternalTexture();
  87136. if (internalTexture) {
  87137. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  87138. }
  87139. _this.onAfterBlurObservable.notifyObservers(_this);
  87140. });
  87141. // Prevent autoClear.
  87142. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87143. };
  87144. /**
  87145. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87146. */
  87147. HighlightLayer.prototype.needStencil = function () {
  87148. return true;
  87149. };
  87150. /**
  87151. * Checks for the readiness of the element composing the layer.
  87152. * @param subMesh the mesh to check for
  87153. * @param useInstances specify wether or not to use instances to render the mesh
  87154. * @param emissiveTexture the associated emissive texture used to generate the glow
  87155. * @return true if ready otherwise, false
  87156. */
  87157. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  87158. var material = subMesh.getMaterial();
  87159. var mesh = subMesh.getRenderingMesh();
  87160. if (!material || !mesh || !this._meshes) {
  87161. return false;
  87162. }
  87163. var emissiveTexture = null;
  87164. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87165. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87166. emissiveTexture = material.emissiveTexture;
  87167. }
  87168. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87169. };
  87170. /**
  87171. * Implementation specific of rendering the generating effect on the main canvas.
  87172. * @param effect The effect used to render through
  87173. */
  87174. HighlightLayer.prototype._internalRender = function (effect) {
  87175. // Texture
  87176. effect.setTexture("textureSampler", this._blurTexture);
  87177. // Cache
  87178. var engine = this._engine;
  87179. var previousStencilBuffer = engine.getStencilBuffer();
  87180. var previousStencilFunction = engine.getStencilFunction();
  87181. var previousStencilMask = engine.getStencilMask();
  87182. var previousStencilOperationPass = engine.getStencilOperationPass();
  87183. var previousStencilOperationFail = engine.getStencilOperationFail();
  87184. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  87185. var previousStencilReference = engine.getStencilFunctionReference();
  87186. // Stencil operations
  87187. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  87188. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  87189. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  87190. // Draw order
  87191. engine.setStencilMask(0x00);
  87192. engine.setStencilBuffer(true);
  87193. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  87194. // 2 passes inner outer
  87195. if (this.outerGlow) {
  87196. effect.setFloat("offset", 0);
  87197. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  87198. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87199. }
  87200. if (this.innerGlow) {
  87201. effect.setFloat("offset", 1);
  87202. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  87203. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87204. }
  87205. // Restore Cache
  87206. engine.setStencilFunction(previousStencilFunction);
  87207. engine.setStencilMask(previousStencilMask);
  87208. engine.setStencilBuffer(previousStencilBuffer);
  87209. engine.setStencilOperationPass(previousStencilOperationPass);
  87210. engine.setStencilOperationFail(previousStencilOperationFail);
  87211. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  87212. engine.setStencilFunctionReference(previousStencilReference);
  87213. };
  87214. /**
  87215. * Returns true if the layer contains information to display, otherwise false.
  87216. */
  87217. HighlightLayer.prototype.shouldRender = function () {
  87218. if (_super.prototype.shouldRender.call(this)) {
  87219. return this._meshes ? true : false;
  87220. }
  87221. return false;
  87222. };
  87223. /**
  87224. * Returns true if the mesh should render, otherwise false.
  87225. * @param mesh The mesh to render
  87226. * @returns true if it should render otherwise false
  87227. */
  87228. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  87229. // Excluded Mesh
  87230. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  87231. return false;
  87232. }
  87233. ;
  87234. return true;
  87235. };
  87236. /**
  87237. * Sets the required values for both the emissive texture and and the main color.
  87238. */
  87239. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87240. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87241. if (highlightLayerMesh) {
  87242. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  87243. }
  87244. else {
  87245. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87246. }
  87247. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87248. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87249. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  87250. }
  87251. else {
  87252. this._emissiveTextureAndColor.texture = null;
  87253. }
  87254. };
  87255. /**
  87256. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  87257. * @param mesh The mesh to exclude from the highlight layer
  87258. */
  87259. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  87260. if (!this._excludedMeshes) {
  87261. return;
  87262. }
  87263. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87264. if (!meshExcluded) {
  87265. this._excludedMeshes[mesh.uniqueId] = {
  87266. mesh: mesh,
  87267. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  87268. mesh.getEngine().setStencilBuffer(false);
  87269. }),
  87270. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  87271. mesh.getEngine().setStencilBuffer(true);
  87272. }),
  87273. };
  87274. }
  87275. };
  87276. /**
  87277. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  87278. * @param mesh The mesh to highlight
  87279. */
  87280. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  87281. if (!this._excludedMeshes) {
  87282. return;
  87283. }
  87284. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87285. if (meshExcluded) {
  87286. if (meshExcluded.beforeRender) {
  87287. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  87288. }
  87289. if (meshExcluded.afterRender) {
  87290. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  87291. }
  87292. }
  87293. this._excludedMeshes[mesh.uniqueId] = null;
  87294. };
  87295. /**
  87296. * Determine if a given mesh will be highlighted by the current HighlightLayer
  87297. * @param mesh mesh to test
  87298. * @returns true if the mesh will be highlighted by the current HighlightLayer
  87299. */
  87300. HighlightLayer.prototype.hasMesh = function (mesh) {
  87301. if (!this._meshes) {
  87302. return false;
  87303. }
  87304. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  87305. };
  87306. /**
  87307. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  87308. * @param mesh The mesh to highlight
  87309. * @param color The color of the highlight
  87310. * @param glowEmissiveOnly Extract the glow from the emissive texture
  87311. */
  87312. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  87313. var _this = this;
  87314. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  87315. if (!this._meshes) {
  87316. return;
  87317. }
  87318. var meshHighlight = this._meshes[mesh.uniqueId];
  87319. if (meshHighlight) {
  87320. meshHighlight.color = color;
  87321. }
  87322. else {
  87323. this._meshes[mesh.uniqueId] = {
  87324. mesh: mesh,
  87325. color: color,
  87326. // Lambda required for capture due to Observable this context
  87327. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87328. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87329. _this._defaultStencilReference(mesh);
  87330. }
  87331. else {
  87332. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87333. }
  87334. }),
  87335. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87336. glowEmissiveOnly: glowEmissiveOnly
  87337. };
  87338. }
  87339. this._shouldRender = true;
  87340. };
  87341. /**
  87342. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87343. * @param mesh The mesh to highlight
  87344. */
  87345. HighlightLayer.prototype.removeMesh = function (mesh) {
  87346. if (!this._meshes) {
  87347. return;
  87348. }
  87349. var meshHighlight = this._meshes[mesh.uniqueId];
  87350. if (meshHighlight) {
  87351. if (meshHighlight.observerHighlight) {
  87352. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87353. }
  87354. if (meshHighlight.observerDefault) {
  87355. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87356. }
  87357. delete this._meshes[mesh.uniqueId];
  87358. }
  87359. this._shouldRender = false;
  87360. for (var meshHighlightToCheck in this._meshes) {
  87361. if (this._meshes[meshHighlightToCheck]) {
  87362. this._shouldRender = true;
  87363. break;
  87364. }
  87365. }
  87366. };
  87367. /**
  87368. * Force the stencil to the normal expected value for none glowing parts
  87369. */
  87370. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87371. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87372. };
  87373. /**
  87374. * Free any resources and references associated to a mesh.
  87375. * Internal use
  87376. * @param mesh The mesh to free.
  87377. */
  87378. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87379. this.removeMesh(mesh);
  87380. this.removeExcludedMesh(mesh);
  87381. };
  87382. /**
  87383. * Dispose the highlight layer and free resources.
  87384. */
  87385. HighlightLayer.prototype.dispose = function () {
  87386. if (this._meshes) {
  87387. // Clean mesh references
  87388. for (var id in this._meshes) {
  87389. var meshHighlight = this._meshes[id];
  87390. if (meshHighlight && meshHighlight.mesh) {
  87391. if (meshHighlight.observerHighlight) {
  87392. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87393. }
  87394. if (meshHighlight.observerDefault) {
  87395. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87396. }
  87397. }
  87398. }
  87399. this._meshes = null;
  87400. }
  87401. if (this._excludedMeshes) {
  87402. for (var id in this._excludedMeshes) {
  87403. var meshHighlight = this._excludedMeshes[id];
  87404. if (meshHighlight) {
  87405. if (meshHighlight.beforeRender) {
  87406. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87407. }
  87408. if (meshHighlight.afterRender) {
  87409. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87410. }
  87411. }
  87412. }
  87413. this._excludedMeshes = null;
  87414. }
  87415. _super.prototype.dispose.call(this);
  87416. };
  87417. /**
  87418. * Effect Name of the highlight layer.
  87419. */
  87420. HighlightLayer.EffectName = "HighlightLayer";
  87421. /**
  87422. * The neutral color used during the preparation of the glow effect.
  87423. * This is black by default as the blend operation is a blend operation.
  87424. */
  87425. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87426. /**
  87427. * Stencil value used for glowing meshes.
  87428. */
  87429. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87430. /**
  87431. * Stencil value used for the other meshes in the scene.
  87432. */
  87433. HighlightLayer.NormalMeshStencilReference = 0x01;
  87434. return HighlightLayer;
  87435. }(BABYLON.EffectLayer));
  87436. BABYLON.HighlightLayer = HighlightLayer;
  87437. })(BABYLON || (BABYLON = {}));
  87438. //# sourceMappingURL=babylon.highlightLayer.js.map
  87439. "use strict";
  87440. var BABYLON;
  87441. (function (BABYLON) {
  87442. /**
  87443. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87444. *
  87445. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87446. * glowy meshes to your scene.
  87447. *
  87448. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87449. */
  87450. var GlowLayer = /** @class */ (function (_super) {
  87451. __extends(GlowLayer, _super);
  87452. /**
  87453. * Instantiates a new glow Layer and references it to the scene.
  87454. * @param name The name of the layer
  87455. * @param scene The scene to use the layer in
  87456. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87457. */
  87458. function GlowLayer(name, scene, options) {
  87459. var _this = _super.call(this, name, scene) || this;
  87460. _this.name = name;
  87461. _this._intensity = 1.0;
  87462. _this._includedOnlyMeshes = [];
  87463. _this._excludedMeshes = [];
  87464. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87465. // Adapt options
  87466. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87467. // Initialize the layer
  87468. _this._init({
  87469. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87470. camera: _this._options.camera,
  87471. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87472. mainTextureRatio: _this._options.mainTextureRatio
  87473. });
  87474. return _this;
  87475. }
  87476. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87477. /**
  87478. * Gets the kernel size of the blur.
  87479. */
  87480. get: function () {
  87481. return this._horizontalBlurPostprocess1.kernel;
  87482. },
  87483. /**
  87484. * Sets the kernel size of the blur.
  87485. */
  87486. set: function (value) {
  87487. this._horizontalBlurPostprocess1.kernel = value;
  87488. this._verticalBlurPostprocess1.kernel = value;
  87489. this._horizontalBlurPostprocess2.kernel = value;
  87490. this._verticalBlurPostprocess2.kernel = value;
  87491. },
  87492. enumerable: true,
  87493. configurable: true
  87494. });
  87495. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87496. /**
  87497. * Gets the glow intensity.
  87498. */
  87499. get: function () {
  87500. return this._intensity;
  87501. },
  87502. /**
  87503. * Sets the glow intensity.
  87504. */
  87505. set: function (value) {
  87506. this._intensity = value;
  87507. },
  87508. enumerable: true,
  87509. configurable: true
  87510. });
  87511. /**
  87512. * Get the effect name of the layer.
  87513. * @return The effect name
  87514. */
  87515. GlowLayer.prototype.getEffectName = function () {
  87516. return GlowLayer.EffectName;
  87517. };
  87518. /**
  87519. * Create the merge effect. This is the shader use to blit the information back
  87520. * to the main canvas at the end of the scene rendering.
  87521. */
  87522. GlowLayer.prototype._createMergeEffect = function () {
  87523. // Effect
  87524. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87525. };
  87526. /**
  87527. * Creates the render target textures and post processes used in the glow layer.
  87528. */
  87529. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87530. var _this = this;
  87531. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87532. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87533. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87534. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87535. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87536. width: blurTextureWidth,
  87537. height: blurTextureHeight
  87538. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87539. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87540. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87541. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87542. this._blurTexture1.renderParticles = false;
  87543. this._blurTexture1.ignoreCameraViewport = true;
  87544. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87545. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87546. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87547. width: blurTextureWidth2,
  87548. height: blurTextureHeight2
  87549. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87550. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87551. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87552. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87553. this._blurTexture2.renderParticles = false;
  87554. this._blurTexture2.ignoreCameraViewport = true;
  87555. this._textures = [this._blurTexture1, this._blurTexture2];
  87556. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87557. width: blurTextureWidth,
  87558. height: blurTextureHeight
  87559. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87560. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87561. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87562. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87563. effect.setTexture("textureSampler", _this._mainTexture);
  87564. });
  87565. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87566. width: blurTextureWidth,
  87567. height: blurTextureHeight
  87568. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87569. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87570. width: blurTextureWidth2,
  87571. height: blurTextureHeight2
  87572. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87573. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87574. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87575. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87576. effect.setTexture("textureSampler", _this._blurTexture1);
  87577. });
  87578. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87579. width: blurTextureWidth2,
  87580. height: blurTextureHeight2
  87581. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87582. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87583. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87584. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87585. this._mainTexture.samples = this._options.mainTextureSamples;
  87586. this._mainTexture.onAfterUnbindObservable.add(function () {
  87587. var internalTexture = _this._blurTexture1.getInternalTexture();
  87588. if (internalTexture) {
  87589. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87590. internalTexture = _this._blurTexture2.getInternalTexture();
  87591. if (internalTexture) {
  87592. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87593. }
  87594. }
  87595. });
  87596. // Prevent autoClear.
  87597. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87598. };
  87599. /**
  87600. * Checks for the readiness of the element composing the layer.
  87601. * @param subMesh the mesh to check for
  87602. * @param useInstances specify wether or not to use instances to render the mesh
  87603. * @param emissiveTexture the associated emissive texture used to generate the glow
  87604. * @return true if ready otherwise, false
  87605. */
  87606. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87607. var material = subMesh.getMaterial();
  87608. var mesh = subMesh.getRenderingMesh();
  87609. if (!material || !mesh) {
  87610. return false;
  87611. }
  87612. var emissiveTexture = material.emissiveTexture;
  87613. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87614. };
  87615. /**
  87616. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87617. */
  87618. GlowLayer.prototype.needStencil = function () {
  87619. return false;
  87620. };
  87621. /**
  87622. * Implementation specific of rendering the generating effect on the main canvas.
  87623. * @param effect The effect used to render through
  87624. */
  87625. GlowLayer.prototype._internalRender = function (effect) {
  87626. // Texture
  87627. effect.setTexture("textureSampler", this._blurTexture1);
  87628. effect.setTexture("textureSampler2", this._blurTexture2);
  87629. effect.setFloat("offset", this._intensity);
  87630. // Cache
  87631. var engine = this._engine;
  87632. var previousStencilBuffer = engine.getStencilBuffer();
  87633. // Draw order
  87634. engine.setStencilBuffer(false);
  87635. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87636. // Draw order
  87637. engine.setStencilBuffer(previousStencilBuffer);
  87638. };
  87639. /**
  87640. * Sets the required values for both the emissive texture and and the main color.
  87641. */
  87642. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87643. var textureLevel = 1.0;
  87644. if (this.customEmissiveTextureSelector) {
  87645. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87646. }
  87647. else {
  87648. if (material) {
  87649. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87650. if (this._emissiveTextureAndColor.texture) {
  87651. textureLevel = this._emissiveTextureAndColor.texture.level;
  87652. }
  87653. }
  87654. else {
  87655. this._emissiveTextureAndColor.texture = null;
  87656. }
  87657. }
  87658. if (this.customEmissiveColorSelector) {
  87659. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87660. }
  87661. else {
  87662. if (material.emissiveColor) {
  87663. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87664. }
  87665. else {
  87666. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87667. }
  87668. }
  87669. };
  87670. /**
  87671. * Returns true if the mesh should render, otherwise false.
  87672. * @param mesh The mesh to render
  87673. * @returns true if it should render otherwise false
  87674. */
  87675. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87676. return this.hasMesh(mesh);
  87677. };
  87678. /**
  87679. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87680. * @param mesh The mesh to exclude from the glow layer
  87681. */
  87682. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87683. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87684. this._excludedMeshes.push(mesh.uniqueId);
  87685. }
  87686. };
  87687. /**
  87688. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87689. * @param mesh The mesh to remove
  87690. */
  87691. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87692. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87693. if (index !== -1) {
  87694. this._excludedMeshes.splice(index, 1);
  87695. }
  87696. };
  87697. /**
  87698. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87699. * @param mesh The mesh to include in the glow layer
  87700. */
  87701. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87702. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87703. this._includedOnlyMeshes.push(mesh.uniqueId);
  87704. }
  87705. };
  87706. /**
  87707. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87708. * @param mesh The mesh to remove
  87709. */
  87710. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87711. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87712. if (index !== -1) {
  87713. this._includedOnlyMeshes.splice(index, 1);
  87714. }
  87715. };
  87716. /**
  87717. * Determine if a given mesh will be used in the glow layer
  87718. * @param mesh The mesh to test
  87719. * @returns true if the mesh will be highlighted by the current glow layer
  87720. */
  87721. GlowLayer.prototype.hasMesh = function (mesh) {
  87722. // Included Mesh
  87723. if (this._includedOnlyMeshes.length) {
  87724. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87725. }
  87726. ;
  87727. // Excluded Mesh
  87728. if (this._excludedMeshes.length) {
  87729. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87730. }
  87731. ;
  87732. return true;
  87733. };
  87734. /**
  87735. * Free any resources and references associated to a mesh.
  87736. * Internal use
  87737. * @param mesh The mesh to free.
  87738. */
  87739. GlowLayer.prototype._disposeMesh = function (mesh) {
  87740. this.removeIncludedOnlyMesh(mesh);
  87741. this.removeExcludedMesh(mesh);
  87742. };
  87743. /**
  87744. * Effect Name of the layer.
  87745. */
  87746. GlowLayer.EffectName = "GlowLayer";
  87747. /**
  87748. * The default blur kernel size used for the glow.
  87749. */
  87750. GlowLayer.DefaultBlurKernelSize = 32;
  87751. /**
  87752. * The default texture size ratio used for the glow.
  87753. */
  87754. GlowLayer.DefaultTextureRatio = 0.5;
  87755. return GlowLayer;
  87756. }(BABYLON.EffectLayer));
  87757. BABYLON.GlowLayer = GlowLayer;
  87758. })(BABYLON || (BABYLON = {}));
  87759. //# sourceMappingURL=babylon.glowLayer.js.map
  87760. "use strict";
  87761. var BABYLON;
  87762. (function (BABYLON) {
  87763. /**
  87764. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87765. */
  87766. var AssetTaskState;
  87767. (function (AssetTaskState) {
  87768. /**
  87769. * Initialization
  87770. */
  87771. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87772. /**
  87773. * Running
  87774. */
  87775. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87776. /**
  87777. * Done
  87778. */
  87779. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87780. /**
  87781. * Error
  87782. */
  87783. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87784. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87785. /**
  87786. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87787. */
  87788. var AbstractAssetTask = /** @class */ (function () {
  87789. /**
  87790. * Creates a new {BABYLON.AssetsManager}
  87791. * @param name defines the name of the task
  87792. */
  87793. function AbstractAssetTask(
  87794. /**
  87795. * Task name
  87796. */ name) {
  87797. this.name = name;
  87798. this._isCompleted = false;
  87799. this._taskState = AssetTaskState.INIT;
  87800. }
  87801. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87802. /**
  87803. * Get if the task is completed
  87804. */
  87805. get: function () {
  87806. return this._isCompleted;
  87807. },
  87808. enumerable: true,
  87809. configurable: true
  87810. });
  87811. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87812. /**
  87813. * Gets the current state of the task
  87814. */
  87815. get: function () {
  87816. return this._taskState;
  87817. },
  87818. enumerable: true,
  87819. configurable: true
  87820. });
  87821. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87822. /**
  87823. * Gets the current error object (if task is in error)
  87824. */
  87825. get: function () {
  87826. return this._errorObject;
  87827. },
  87828. enumerable: true,
  87829. configurable: true
  87830. });
  87831. /**
  87832. * Internal only
  87833. * @ignore
  87834. */
  87835. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87836. if (this._errorObject) {
  87837. return;
  87838. }
  87839. this._errorObject = {
  87840. message: message,
  87841. exception: exception
  87842. };
  87843. };
  87844. /**
  87845. * Execute the current task
  87846. * @param scene defines the scene where you want your assets to be loaded
  87847. * @param onSuccess is a callback called when the task is successfully executed
  87848. * @param onError is a callback called if an error occurs
  87849. */
  87850. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87851. var _this = this;
  87852. this._taskState = AssetTaskState.RUNNING;
  87853. this.runTask(scene, function () {
  87854. _this.onDoneCallback(onSuccess, onError);
  87855. }, function (msg, exception) {
  87856. _this.onErrorCallback(onError, msg, exception);
  87857. });
  87858. };
  87859. /**
  87860. * Execute the current task
  87861. * @param scene defines the scene where you want your assets to be loaded
  87862. * @param onSuccess is a callback called when the task is successfully executed
  87863. * @param onError is a callback called if an error occurs
  87864. */
  87865. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87866. throw new Error("runTask is not implemented");
  87867. };
  87868. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87869. this._taskState = AssetTaskState.ERROR;
  87870. this._errorObject = {
  87871. message: message,
  87872. exception: exception
  87873. };
  87874. if (this.onError) {
  87875. this.onError(this, message, exception);
  87876. }
  87877. onError();
  87878. };
  87879. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87880. try {
  87881. this._taskState = AssetTaskState.DONE;
  87882. this._isCompleted = true;
  87883. if (this.onSuccess) {
  87884. this.onSuccess(this);
  87885. }
  87886. onSuccess();
  87887. }
  87888. catch (e) {
  87889. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87890. }
  87891. };
  87892. return AbstractAssetTask;
  87893. }());
  87894. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87895. /**
  87896. * Class used to share progress information about assets loading
  87897. */
  87898. var AssetsProgressEvent = /** @class */ (function () {
  87899. /**
  87900. * Creates a {BABYLON.AssetsProgressEvent}
  87901. * @param remainingCount defines the number of remaining tasks to process
  87902. * @param totalCount defines the total number of tasks
  87903. * @param task defines the task that was just processed
  87904. */
  87905. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87906. this.remainingCount = remainingCount;
  87907. this.totalCount = totalCount;
  87908. this.task = task;
  87909. }
  87910. return AssetsProgressEvent;
  87911. }());
  87912. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87913. /**
  87914. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87915. */
  87916. var MeshAssetTask = /** @class */ (function (_super) {
  87917. __extends(MeshAssetTask, _super);
  87918. /**
  87919. * Creates a new {BABYLON.MeshAssetTask}
  87920. * @param name defines the name of the task
  87921. * @param meshesNames defines the list of mesh's names you want to load
  87922. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87923. * @param sceneFilename defines the filename of the scene to load from
  87924. */
  87925. function MeshAssetTask(
  87926. /**
  87927. * Defines the name of the task
  87928. */
  87929. name,
  87930. /**
  87931. * Defines the list of mesh's names you want to load
  87932. */
  87933. meshesNames,
  87934. /**
  87935. * Defines the root url to use as a base to load your meshes and associated resources
  87936. */
  87937. rootUrl,
  87938. /**
  87939. * Defines the filename of the scene to load from
  87940. */
  87941. sceneFilename) {
  87942. var _this = _super.call(this, name) || this;
  87943. _this.name = name;
  87944. _this.meshesNames = meshesNames;
  87945. _this.rootUrl = rootUrl;
  87946. _this.sceneFilename = sceneFilename;
  87947. return _this;
  87948. }
  87949. /**
  87950. * Execute the current task
  87951. * @param scene defines the scene where you want your assets to be loaded
  87952. * @param onSuccess is a callback called when the task is successfully executed
  87953. * @param onError is a callback called if an error occurs
  87954. */
  87955. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87956. var _this = this;
  87957. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87958. _this.loadedMeshes = meshes;
  87959. _this.loadedParticleSystems = particleSystems;
  87960. _this.loadedSkeletons = skeletons;
  87961. onSuccess();
  87962. }, null, function (scene, message, exception) {
  87963. onError(message, exception);
  87964. });
  87965. };
  87966. return MeshAssetTask;
  87967. }(AbstractAssetTask));
  87968. BABYLON.MeshAssetTask = MeshAssetTask;
  87969. /**
  87970. * Define a task used by {BABYLON.AssetsManager} to load text content
  87971. */
  87972. var TextFileAssetTask = /** @class */ (function (_super) {
  87973. __extends(TextFileAssetTask, _super);
  87974. /**
  87975. * Creates a new TextFileAssetTask object
  87976. * @param name defines the name of the task
  87977. * @param url defines the location of the file to load
  87978. */
  87979. function TextFileAssetTask(
  87980. /**
  87981. * Defines the name of the task
  87982. */
  87983. name,
  87984. /**
  87985. * Defines the location of the file to load
  87986. */
  87987. url) {
  87988. var _this = _super.call(this, name) || this;
  87989. _this.name = name;
  87990. _this.url = url;
  87991. return _this;
  87992. }
  87993. /**
  87994. * Execute the current task
  87995. * @param scene defines the scene where you want your assets to be loaded
  87996. * @param onSuccess is a callback called when the task is successfully executed
  87997. * @param onError is a callback called if an error occurs
  87998. */
  87999. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88000. var _this = this;
  88001. scene._loadFile(this.url, function (data) {
  88002. _this.text = data;
  88003. onSuccess();
  88004. }, undefined, false, false, function (request, exception) {
  88005. if (request) {
  88006. onError(request.status + " " + request.statusText, exception);
  88007. }
  88008. });
  88009. };
  88010. return TextFileAssetTask;
  88011. }(AbstractAssetTask));
  88012. BABYLON.TextFileAssetTask = TextFileAssetTask;
  88013. /**
  88014. * Define a task used by {BABYLON.AssetsManager} to load binary data
  88015. */
  88016. var BinaryFileAssetTask = /** @class */ (function (_super) {
  88017. __extends(BinaryFileAssetTask, _super);
  88018. /**
  88019. * Creates a new BinaryFileAssetTask object
  88020. * @param name defines the name of the new task
  88021. * @param url defines the location of the file to load
  88022. */
  88023. function BinaryFileAssetTask(
  88024. /**
  88025. * Defines the name of the task
  88026. */
  88027. name,
  88028. /**
  88029. * Defines the location of the file to load
  88030. */
  88031. url) {
  88032. var _this = _super.call(this, name) || this;
  88033. _this.name = name;
  88034. _this.url = url;
  88035. return _this;
  88036. }
  88037. /**
  88038. * Execute the current task
  88039. * @param scene defines the scene where you want your assets to be loaded
  88040. * @param onSuccess is a callback called when the task is successfully executed
  88041. * @param onError is a callback called if an error occurs
  88042. */
  88043. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88044. var _this = this;
  88045. scene._loadFile(this.url, function (data) {
  88046. _this.data = data;
  88047. onSuccess();
  88048. }, undefined, true, true, function (request, exception) {
  88049. if (request) {
  88050. onError(request.status + " " + request.statusText, exception);
  88051. }
  88052. });
  88053. };
  88054. return BinaryFileAssetTask;
  88055. }(AbstractAssetTask));
  88056. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  88057. /**
  88058. * Define a task used by {BABYLON.AssetsManager} to load images
  88059. */
  88060. var ImageAssetTask = /** @class */ (function (_super) {
  88061. __extends(ImageAssetTask, _super);
  88062. /**
  88063. * Creates a new ImageAssetTask
  88064. * @param name defines the name of the task
  88065. * @param url defines the location of the image to load
  88066. */
  88067. function ImageAssetTask(
  88068. /**
  88069. * Defines the name of the task
  88070. */
  88071. name,
  88072. /**
  88073. * Defines the location of the image to load
  88074. */
  88075. url) {
  88076. var _this = _super.call(this, name) || this;
  88077. _this.name = name;
  88078. _this.url = url;
  88079. return _this;
  88080. }
  88081. /**
  88082. * Execute the current task
  88083. * @param scene defines the scene where you want your assets to be loaded
  88084. * @param onSuccess is a callback called when the task is successfully executed
  88085. * @param onError is a callback called if an error occurs
  88086. */
  88087. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88088. var _this = this;
  88089. var img = new Image();
  88090. BABYLON.Tools.SetCorsBehavior(this.url, img);
  88091. img.onload = function () {
  88092. _this.image = img;
  88093. onSuccess();
  88094. };
  88095. img.onerror = function (err) {
  88096. onError("Error loading image", err);
  88097. };
  88098. img.src = this.url;
  88099. };
  88100. return ImageAssetTask;
  88101. }(AbstractAssetTask));
  88102. BABYLON.ImageAssetTask = ImageAssetTask;
  88103. /**
  88104. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  88105. */
  88106. var TextureAssetTask = /** @class */ (function (_super) {
  88107. __extends(TextureAssetTask, _super);
  88108. /**
  88109. * Creates a new TextureAssetTask object
  88110. * @param name defines the name of the task
  88111. * @param url defines the location of the file to load
  88112. * @param noMipmap defines if mipmap should not be generated (default is false)
  88113. * @param invertY defines if texture must be inverted on Y axis (default is false)
  88114. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88115. */
  88116. function TextureAssetTask(
  88117. /**
  88118. * Defines the name of the task
  88119. */
  88120. name,
  88121. /**
  88122. * Defines the location of the file to load
  88123. */
  88124. url,
  88125. /**
  88126. * Defines if mipmap should not be generated (default is false)
  88127. */
  88128. noMipmap,
  88129. /**
  88130. * Defines if texture must be inverted on Y axis (default is false)
  88131. */
  88132. invertY,
  88133. /**
  88134. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88135. */
  88136. samplingMode) {
  88137. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88138. var _this = _super.call(this, name) || this;
  88139. _this.name = name;
  88140. _this.url = url;
  88141. _this.noMipmap = noMipmap;
  88142. _this.invertY = invertY;
  88143. _this.samplingMode = samplingMode;
  88144. return _this;
  88145. }
  88146. /**
  88147. * Execute the current task
  88148. * @param scene defines the scene where you want your assets to be loaded
  88149. * @param onSuccess is a callback called when the task is successfully executed
  88150. * @param onError is a callback called if an error occurs
  88151. */
  88152. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88153. var onload = function () {
  88154. onSuccess();
  88155. };
  88156. var onerror = function (message, exception) {
  88157. onError(message, exception);
  88158. };
  88159. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  88160. };
  88161. return TextureAssetTask;
  88162. }(AbstractAssetTask));
  88163. BABYLON.TextureAssetTask = TextureAssetTask;
  88164. /**
  88165. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  88166. */
  88167. var CubeTextureAssetTask = /** @class */ (function (_super) {
  88168. __extends(CubeTextureAssetTask, _super);
  88169. /**
  88170. * Creates a new CubeTextureAssetTask
  88171. * @param name defines the name of the task
  88172. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88173. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88174. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88175. * @param files defines the explicit list of files (undefined by default)
  88176. */
  88177. function CubeTextureAssetTask(
  88178. /**
  88179. * Defines the name of the task
  88180. */
  88181. name,
  88182. /**
  88183. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88184. */
  88185. url,
  88186. /**
  88187. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88188. */
  88189. extensions,
  88190. /**
  88191. * Defines if mipmaps should not be generated (default is false)
  88192. */
  88193. noMipmap,
  88194. /**
  88195. * Defines the explicit list of files (undefined by default)
  88196. */
  88197. files) {
  88198. var _this = _super.call(this, name) || this;
  88199. _this.name = name;
  88200. _this.url = url;
  88201. _this.extensions = extensions;
  88202. _this.noMipmap = noMipmap;
  88203. _this.files = files;
  88204. return _this;
  88205. }
  88206. /**
  88207. * Execute the current task
  88208. * @param scene defines the scene where you want your assets to be loaded
  88209. * @param onSuccess is a callback called when the task is successfully executed
  88210. * @param onError is a callback called if an error occurs
  88211. */
  88212. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88213. var onload = function () {
  88214. onSuccess();
  88215. };
  88216. var onerror = function (message, exception) {
  88217. onError(message, exception);
  88218. };
  88219. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  88220. };
  88221. return CubeTextureAssetTask;
  88222. }(AbstractAssetTask));
  88223. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  88224. /**
  88225. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  88226. */
  88227. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  88228. __extends(HDRCubeTextureAssetTask, _super);
  88229. /**
  88230. * Creates a new HDRCubeTextureAssetTask object
  88231. * @param name defines the name of the task
  88232. * @param url defines the location of the file to load
  88233. * @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.
  88234. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88235. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88236. * @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)
  88237. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88238. */
  88239. function HDRCubeTextureAssetTask(
  88240. /**
  88241. * Defines the name of the task
  88242. */
  88243. name,
  88244. /**
  88245. * Defines the location of the file to load
  88246. */
  88247. url,
  88248. /**
  88249. * 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.
  88250. */
  88251. size,
  88252. /**
  88253. * Defines if mipmaps should not be generated (default is false)
  88254. */
  88255. noMipmap,
  88256. /**
  88257. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88258. */
  88259. generateHarmonics,
  88260. /**
  88261. * 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)
  88262. */
  88263. useInGammaSpace,
  88264. /**
  88265. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88266. */
  88267. usePMREMGenerator) {
  88268. if (noMipmap === void 0) { noMipmap = false; }
  88269. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88270. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88271. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88272. var _this = _super.call(this, name) || this;
  88273. _this.name = name;
  88274. _this.url = url;
  88275. _this.size = size;
  88276. _this.noMipmap = noMipmap;
  88277. _this.generateHarmonics = generateHarmonics;
  88278. _this.useInGammaSpace = useInGammaSpace;
  88279. _this.usePMREMGenerator = usePMREMGenerator;
  88280. return _this;
  88281. }
  88282. /**
  88283. * Execute the current task
  88284. * @param scene defines the scene where you want your assets to be loaded
  88285. * @param onSuccess is a callback called when the task is successfully executed
  88286. * @param onError is a callback called if an error occurs
  88287. */
  88288. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88289. var onload = function () {
  88290. onSuccess();
  88291. };
  88292. var onerror = function (message, exception) {
  88293. onError(message, exception);
  88294. };
  88295. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  88296. };
  88297. return HDRCubeTextureAssetTask;
  88298. }(AbstractAssetTask));
  88299. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  88300. /**
  88301. * This class can be used to easily import assets into a scene
  88302. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  88303. */
  88304. var AssetsManager = /** @class */ (function () {
  88305. /**
  88306. * Creates a new AssetsManager
  88307. * @param scene defines the scene to work on
  88308. */
  88309. function AssetsManager(scene) {
  88310. this._isLoading = false;
  88311. this._tasks = new Array();
  88312. this._waitingTasksCount = 0;
  88313. this._totalTasksCount = 0;
  88314. /**
  88315. * Observable called when all tasks are processed
  88316. */
  88317. this.onTaskSuccessObservable = new BABYLON.Observable();
  88318. /**
  88319. * Observable called when a task had an error
  88320. */
  88321. this.onTaskErrorObservable = new BABYLON.Observable();
  88322. /**
  88323. * Observable called when a task is successful
  88324. */
  88325. this.onTasksDoneObservable = new BABYLON.Observable();
  88326. /**
  88327. * Observable called when a task is done (whatever the result is)
  88328. */
  88329. this.onProgressObservable = new BABYLON.Observable();
  88330. /**
  88331. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88332. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88333. */
  88334. this.useDefaultLoadingScreen = true;
  88335. this._scene = scene;
  88336. }
  88337. /**
  88338. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88339. * @param taskName defines the name of the new task
  88340. * @param meshesNames defines the name of meshes to load
  88341. * @param rootUrl defines the root url to use to locate files
  88342. * @param sceneFilename defines the filename of the scene file
  88343. * @returns a new {BABYLON.MeshAssetTask} object
  88344. */
  88345. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88346. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88347. this._tasks.push(task);
  88348. return task;
  88349. };
  88350. /**
  88351. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88352. * @param taskName defines the name of the new task
  88353. * @param url defines the url of the file to load
  88354. * @returns a new {BABYLON.TextFileAssetTask} object
  88355. */
  88356. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88357. var task = new TextFileAssetTask(taskName, url);
  88358. this._tasks.push(task);
  88359. return task;
  88360. };
  88361. /**
  88362. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88363. * @param taskName defines the name of the new task
  88364. * @param url defines the url of the file to load
  88365. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88366. */
  88367. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88368. var task = new BinaryFileAssetTask(taskName, url);
  88369. this._tasks.push(task);
  88370. return task;
  88371. };
  88372. /**
  88373. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88374. * @param taskName defines the name of the new task
  88375. * @param url defines the url of the file to load
  88376. * @returns a new {BABYLON.ImageAssetTask} object
  88377. */
  88378. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88379. var task = new ImageAssetTask(taskName, url);
  88380. this._tasks.push(task);
  88381. return task;
  88382. };
  88383. /**
  88384. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88385. * @param taskName defines the name of the new task
  88386. * @param url defines the url of the file to load
  88387. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88388. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88389. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88390. * @returns a new {BABYLON.TextureAssetTask} object
  88391. */
  88392. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88394. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88395. this._tasks.push(task);
  88396. return task;
  88397. };
  88398. /**
  88399. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88400. * @param taskName defines the name of the new task
  88401. * @param url defines the url of the file to load
  88402. * @param extensions defines the extension to use to load the cube map (can be null)
  88403. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88404. * @param files defines the list of files to load (can be null)
  88405. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88406. */
  88407. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88408. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88409. this._tasks.push(task);
  88410. return task;
  88411. };
  88412. /**
  88413. *
  88414. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88415. * @param taskName defines the name of the new task
  88416. * @param url defines the url of the file to load
  88417. * @param size defines the size you want for the cubemap (can be null)
  88418. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88419. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88420. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88421. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88422. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88423. */
  88424. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88425. if (noMipmap === void 0) { noMipmap = false; }
  88426. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88427. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88428. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88429. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88430. this._tasks.push(task);
  88431. return task;
  88432. };
  88433. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88434. var _this = this;
  88435. this._waitingTasksCount--;
  88436. try {
  88437. if (task.taskState === AssetTaskState.DONE) {
  88438. // Let's remove successfull tasks
  88439. BABYLON.Tools.SetImmediate(function () {
  88440. var index = _this._tasks.indexOf(task);
  88441. if (index > -1) {
  88442. _this._tasks.splice(index, 1);
  88443. }
  88444. });
  88445. }
  88446. if (this.onProgress) {
  88447. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88448. }
  88449. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88450. }
  88451. catch (e) {
  88452. BABYLON.Tools.Error("Error running progress callbacks.");
  88453. console.log(e);
  88454. }
  88455. if (this._waitingTasksCount === 0) {
  88456. try {
  88457. if (this.onFinish) {
  88458. this.onFinish(this._tasks);
  88459. }
  88460. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88461. }
  88462. catch (e) {
  88463. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88464. console.log(e);
  88465. }
  88466. this._isLoading = false;
  88467. this._scene.getEngine().hideLoadingUI();
  88468. }
  88469. };
  88470. AssetsManager.prototype._runTask = function (task) {
  88471. var _this = this;
  88472. var done = function () {
  88473. try {
  88474. if (_this.onTaskSuccess) {
  88475. _this.onTaskSuccess(task);
  88476. }
  88477. _this.onTaskSuccessObservable.notifyObservers(task);
  88478. _this._decreaseWaitingTasksCount(task);
  88479. }
  88480. catch (e) {
  88481. error("Error executing task success callbacks", e);
  88482. }
  88483. };
  88484. var error = function (message, exception) {
  88485. task._setErrorObject(message, exception);
  88486. if (_this.onTaskError) {
  88487. _this.onTaskError(task);
  88488. }
  88489. _this.onTaskErrorObservable.notifyObservers(task);
  88490. _this._decreaseWaitingTasksCount(task);
  88491. };
  88492. task.run(this._scene, done, error);
  88493. };
  88494. /**
  88495. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88496. * @return the current instance of the {BABYLON.AssetsManager}
  88497. */
  88498. AssetsManager.prototype.reset = function () {
  88499. this._isLoading = false;
  88500. this._tasks = new Array();
  88501. return this;
  88502. };
  88503. /**
  88504. * Start the loading process
  88505. * @return the current instance of the {BABYLON.AssetsManager}
  88506. */
  88507. AssetsManager.prototype.load = function () {
  88508. if (this._isLoading) {
  88509. return this;
  88510. }
  88511. this._isLoading = true;
  88512. this._waitingTasksCount = this._tasks.length;
  88513. this._totalTasksCount = this._tasks.length;
  88514. if (this._waitingTasksCount === 0) {
  88515. this._isLoading = false;
  88516. if (this.onFinish) {
  88517. this.onFinish(this._tasks);
  88518. }
  88519. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88520. return this;
  88521. }
  88522. if (this.useDefaultLoadingScreen) {
  88523. this._scene.getEngine().displayLoadingUI();
  88524. }
  88525. for (var index = 0; index < this._tasks.length; index++) {
  88526. var task = this._tasks[index];
  88527. this._runTask(task);
  88528. }
  88529. return this;
  88530. };
  88531. return AssetsManager;
  88532. }());
  88533. BABYLON.AssetsManager = AssetsManager;
  88534. })(BABYLON || (BABYLON = {}));
  88535. //# sourceMappingURL=babylon.assetsManager.js.map
  88536. "use strict";
  88537. var BABYLON;
  88538. (function (BABYLON) {
  88539. var serializedGeometries = [];
  88540. var serializeGeometry = function (geometry, serializationGeometries) {
  88541. if (serializedGeometries[geometry.id]) {
  88542. return;
  88543. }
  88544. if (geometry.doNotSerialize) {
  88545. return;
  88546. }
  88547. if (geometry instanceof BABYLON.BoxGeometry) {
  88548. serializationGeometries.boxes.push(geometry.serialize());
  88549. }
  88550. else if (geometry instanceof BABYLON.SphereGeometry) {
  88551. serializationGeometries.spheres.push(geometry.serialize());
  88552. }
  88553. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88554. serializationGeometries.cylinders.push(geometry.serialize());
  88555. }
  88556. else if (geometry instanceof BABYLON.TorusGeometry) {
  88557. serializationGeometries.toruses.push(geometry.serialize());
  88558. }
  88559. else if (geometry instanceof BABYLON.GroundGeometry) {
  88560. serializationGeometries.grounds.push(geometry.serialize());
  88561. }
  88562. else if (geometry instanceof BABYLON.Plane) {
  88563. serializationGeometries.planes.push(geometry.serialize());
  88564. }
  88565. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88566. serializationGeometries.torusKnots.push(geometry.serialize());
  88567. }
  88568. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88569. throw new Error("Unknown primitive type");
  88570. }
  88571. else {
  88572. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88573. }
  88574. serializedGeometries[geometry.id] = true;
  88575. };
  88576. var serializeMesh = function (mesh, serializationScene) {
  88577. var serializationObject = {};
  88578. // Geometry
  88579. var geometry = mesh._geometry;
  88580. if (geometry) {
  88581. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88582. // 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
  88583. serializeGeometry(geometry, serializationScene.geometries);
  88584. }
  88585. }
  88586. // Custom
  88587. if (mesh.serialize) {
  88588. mesh.serialize(serializationObject);
  88589. }
  88590. return serializationObject;
  88591. };
  88592. var finalizeSingleMesh = function (mesh, serializationObject) {
  88593. //only works if the mesh is already loaded
  88594. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88595. //serialize material
  88596. if (mesh.material) {
  88597. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88598. serializationObject.materials = serializationObject.materials || [];
  88599. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88600. serializationObject.materials.push(mesh.material.serialize());
  88601. }
  88602. }
  88603. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88604. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88605. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88606. serializationObject.multiMaterials.push(mesh.material.serialize());
  88607. }
  88608. }
  88609. }
  88610. //serialize geometry
  88611. var geometry = mesh._geometry;
  88612. if (geometry) {
  88613. if (!serializationObject.geometries) {
  88614. serializationObject.geometries = {};
  88615. serializationObject.geometries.boxes = [];
  88616. serializationObject.geometries.spheres = [];
  88617. serializationObject.geometries.cylinders = [];
  88618. serializationObject.geometries.toruses = [];
  88619. serializationObject.geometries.grounds = [];
  88620. serializationObject.geometries.planes = [];
  88621. serializationObject.geometries.torusKnots = [];
  88622. serializationObject.geometries.vertexData = [];
  88623. }
  88624. serializeGeometry(geometry, serializationObject.geometries);
  88625. }
  88626. // Skeletons
  88627. if (mesh.skeleton) {
  88628. serializationObject.skeletons = serializationObject.skeletons || [];
  88629. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88630. }
  88631. //serialize the actual mesh
  88632. serializationObject.meshes = serializationObject.meshes || [];
  88633. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88634. }
  88635. };
  88636. var SceneSerializer = /** @class */ (function () {
  88637. function SceneSerializer() {
  88638. }
  88639. SceneSerializer.ClearCache = function () {
  88640. serializedGeometries = [];
  88641. };
  88642. SceneSerializer.Serialize = function (scene) {
  88643. var serializationObject = {};
  88644. SceneSerializer.ClearCache();
  88645. // Scene
  88646. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88647. serializationObject.autoClear = scene.autoClear;
  88648. serializationObject.clearColor = scene.clearColor.asArray();
  88649. serializationObject.ambientColor = scene.ambientColor.asArray();
  88650. serializationObject.gravity = scene.gravity.asArray();
  88651. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88652. serializationObject.workerCollisions = scene.workerCollisions;
  88653. // Fog
  88654. if (scene.fogMode && scene.fogMode !== 0) {
  88655. serializationObject.fogMode = scene.fogMode;
  88656. serializationObject.fogColor = scene.fogColor.asArray();
  88657. serializationObject.fogStart = scene.fogStart;
  88658. serializationObject.fogEnd = scene.fogEnd;
  88659. serializationObject.fogDensity = scene.fogDensity;
  88660. }
  88661. //Physics
  88662. if (scene.isPhysicsEnabled()) {
  88663. var physicEngine = scene.getPhysicsEngine();
  88664. if (physicEngine) {
  88665. serializationObject.physicsEnabled = true;
  88666. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88667. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88668. }
  88669. }
  88670. // Metadata
  88671. if (scene.metadata) {
  88672. serializationObject.metadata = scene.metadata;
  88673. }
  88674. // Morph targets
  88675. serializationObject.morphTargetManagers = [];
  88676. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88677. var abstractMesh = _a[_i];
  88678. var manager = abstractMesh.morphTargetManager;
  88679. if (manager) {
  88680. serializationObject.morphTargetManagers.push(manager.serialize());
  88681. }
  88682. }
  88683. // Lights
  88684. serializationObject.lights = [];
  88685. var index;
  88686. var light;
  88687. for (index = 0; index < scene.lights.length; index++) {
  88688. light = scene.lights[index];
  88689. if (!light.doNotSerialize) {
  88690. serializationObject.lights.push(light.serialize());
  88691. }
  88692. }
  88693. // Cameras
  88694. serializationObject.cameras = [];
  88695. for (index = 0; index < scene.cameras.length; index++) {
  88696. var camera = scene.cameras[index];
  88697. if (!camera.doNotSerialize) {
  88698. serializationObject.cameras.push(camera.serialize());
  88699. }
  88700. }
  88701. if (scene.activeCamera) {
  88702. serializationObject.activeCameraID = scene.activeCamera.id;
  88703. }
  88704. // Animations
  88705. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88706. // Materials
  88707. serializationObject.materials = [];
  88708. serializationObject.multiMaterials = [];
  88709. var material;
  88710. for (index = 0; index < scene.materials.length; index++) {
  88711. material = scene.materials[index];
  88712. if (!material.doNotSerialize) {
  88713. serializationObject.materials.push(material.serialize());
  88714. }
  88715. }
  88716. // MultiMaterials
  88717. serializationObject.multiMaterials = [];
  88718. for (index = 0; index < scene.multiMaterials.length; index++) {
  88719. var multiMaterial = scene.multiMaterials[index];
  88720. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88721. }
  88722. // Environment texture
  88723. if (scene.environmentTexture) {
  88724. serializationObject.environmentTexture = scene.environmentTexture.name;
  88725. }
  88726. // Skeletons
  88727. serializationObject.skeletons = [];
  88728. for (index = 0; index < scene.skeletons.length; index++) {
  88729. var skeleton = scene.skeletons[index];
  88730. if (!skeleton.doNotSerialize) {
  88731. serializationObject.skeletons.push(skeleton.serialize());
  88732. }
  88733. }
  88734. // Transform nodes
  88735. serializationObject.transformNodes = [];
  88736. for (index = 0; index < scene.transformNodes.length; index++) {
  88737. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88738. }
  88739. // Geometries
  88740. serializationObject.geometries = {};
  88741. serializationObject.geometries.boxes = [];
  88742. serializationObject.geometries.spheres = [];
  88743. serializationObject.geometries.cylinders = [];
  88744. serializationObject.geometries.toruses = [];
  88745. serializationObject.geometries.grounds = [];
  88746. serializationObject.geometries.planes = [];
  88747. serializationObject.geometries.torusKnots = [];
  88748. serializationObject.geometries.vertexData = [];
  88749. serializedGeometries = [];
  88750. var geometries = scene.getGeometries();
  88751. for (index = 0; index < geometries.length; index++) {
  88752. var geometry = geometries[index];
  88753. if (geometry.isReady()) {
  88754. serializeGeometry(geometry, serializationObject.geometries);
  88755. }
  88756. }
  88757. // Meshes
  88758. serializationObject.meshes = [];
  88759. for (index = 0; index < scene.meshes.length; index++) {
  88760. var abstractMesh = scene.meshes[index];
  88761. if (abstractMesh instanceof BABYLON.Mesh) {
  88762. var mesh = abstractMesh;
  88763. if (!mesh.doNotSerialize) {
  88764. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88765. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88766. }
  88767. }
  88768. }
  88769. }
  88770. // Particles Systems
  88771. serializationObject.particleSystems = [];
  88772. for (index = 0; index < scene.particleSystems.length; index++) {
  88773. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88774. }
  88775. // Lens flares
  88776. serializationObject.lensFlareSystems = [];
  88777. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88778. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88779. }
  88780. // Shadows
  88781. serializationObject.shadowGenerators = [];
  88782. for (index = 0; index < scene.lights.length; index++) {
  88783. light = scene.lights[index];
  88784. var shadowGenerator = light.getShadowGenerator();
  88785. if (shadowGenerator) {
  88786. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88787. }
  88788. }
  88789. // Action Manager
  88790. if (scene.actionManager) {
  88791. serializationObject.actions = scene.actionManager.serialize("scene");
  88792. }
  88793. // Audio
  88794. serializationObject.sounds = [];
  88795. for (index = 0; index < scene.soundTracks.length; index++) {
  88796. var soundtrack = scene.soundTracks[index];
  88797. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88798. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88799. }
  88800. }
  88801. return serializationObject;
  88802. };
  88803. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88804. if (withParents === void 0) { withParents = false; }
  88805. if (withChildren === void 0) { withChildren = false; }
  88806. var serializationObject = {};
  88807. SceneSerializer.ClearCache();
  88808. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88809. if (withParents || withChildren) {
  88810. //deliberate for loop! not for each, appended should be processed as well.
  88811. for (var i = 0; i < toSerialize.length; ++i) {
  88812. if (withChildren) {
  88813. toSerialize[i].getDescendants().forEach(function (node) {
  88814. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88815. toSerialize.push(node);
  88816. }
  88817. });
  88818. }
  88819. //make sure the array doesn't contain the object already
  88820. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88821. toSerialize.push(toSerialize[i].parent);
  88822. }
  88823. }
  88824. }
  88825. toSerialize.forEach(function (mesh) {
  88826. finalizeSingleMesh(mesh, serializationObject);
  88827. });
  88828. return serializationObject;
  88829. };
  88830. return SceneSerializer;
  88831. }());
  88832. BABYLON.SceneSerializer = SceneSerializer;
  88833. })(BABYLON || (BABYLON = {}));
  88834. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88835. "use strict";
  88836. var BABYLON;
  88837. (function (BABYLON) {
  88838. var ReflectionProbe = /** @class */ (function () {
  88839. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88840. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88841. var _this = this;
  88842. this.name = name;
  88843. this._viewMatrix = BABYLON.Matrix.Identity();
  88844. this._target = BABYLON.Vector3.Zero();
  88845. this._add = BABYLON.Vector3.Zero();
  88846. this._invertYAxis = false;
  88847. this.position = BABYLON.Vector3.Zero();
  88848. this._scene = scene;
  88849. this._scene.reflectionProbes.push(this);
  88850. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88851. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88852. switch (faceIndex) {
  88853. case 0:
  88854. _this._add.copyFromFloats(1, 0, 0);
  88855. break;
  88856. case 1:
  88857. _this._add.copyFromFloats(-1, 0, 0);
  88858. break;
  88859. case 2:
  88860. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88861. break;
  88862. case 3:
  88863. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88864. break;
  88865. case 4:
  88866. _this._add.copyFromFloats(0, 0, 1);
  88867. break;
  88868. case 5:
  88869. _this._add.copyFromFloats(0, 0, -1);
  88870. break;
  88871. }
  88872. if (_this._attachedMesh) {
  88873. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88874. }
  88875. _this.position.addToRef(_this._add, _this._target);
  88876. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88877. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88878. scene._forcedViewPosition = _this.position;
  88879. });
  88880. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88881. scene._forcedViewPosition = null;
  88882. scene.updateTransformMatrix(true);
  88883. });
  88884. if (scene.activeCamera) {
  88885. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88886. }
  88887. }
  88888. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88889. get: function () {
  88890. return this._renderTargetTexture.samples;
  88891. },
  88892. set: function (value) {
  88893. this._renderTargetTexture.samples = value;
  88894. },
  88895. enumerable: true,
  88896. configurable: true
  88897. });
  88898. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88899. get: function () {
  88900. return this._renderTargetTexture.refreshRate;
  88901. },
  88902. set: function (value) {
  88903. this._renderTargetTexture.refreshRate = value;
  88904. },
  88905. enumerable: true,
  88906. configurable: true
  88907. });
  88908. ReflectionProbe.prototype.getScene = function () {
  88909. return this._scene;
  88910. };
  88911. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88912. get: function () {
  88913. return this._renderTargetTexture;
  88914. },
  88915. enumerable: true,
  88916. configurable: true
  88917. });
  88918. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88919. get: function () {
  88920. return this._renderTargetTexture.renderList;
  88921. },
  88922. enumerable: true,
  88923. configurable: true
  88924. });
  88925. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88926. this._attachedMesh = mesh;
  88927. };
  88928. /**
  88929. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88930. *
  88931. * @param renderingGroupId The rendering group id corresponding to its index
  88932. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88933. */
  88934. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88935. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88936. };
  88937. ReflectionProbe.prototype.dispose = function () {
  88938. var index = this._scene.reflectionProbes.indexOf(this);
  88939. if (index !== -1) {
  88940. // Remove from the scene if found
  88941. this._scene.reflectionProbes.splice(index, 1);
  88942. }
  88943. if (this._renderTargetTexture) {
  88944. this._renderTargetTexture.dispose();
  88945. this._renderTargetTexture = null;
  88946. }
  88947. };
  88948. return ReflectionProbe;
  88949. }());
  88950. BABYLON.ReflectionProbe = ReflectionProbe;
  88951. })(BABYLON || (BABYLON = {}));
  88952. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88953. "use strict";
  88954. var BABYLON;
  88955. (function (BABYLON) {
  88956. var Layer = /** @class */ (function () {
  88957. function Layer(name, imgUrl, scene, isBackground, color) {
  88958. this.name = name;
  88959. this.scale = new BABYLON.Vector2(1, 1);
  88960. this.offset = new BABYLON.Vector2(0, 0);
  88961. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88962. this.layerMask = 0x0FFFFFFF;
  88963. this._vertexBuffers = {};
  88964. // Events
  88965. /**
  88966. * An event triggered when the layer is disposed.
  88967. * @type {BABYLON.Observable}
  88968. */
  88969. this.onDisposeObservable = new BABYLON.Observable();
  88970. /**
  88971. * An event triggered before rendering the scene
  88972. * @type {BABYLON.Observable}
  88973. */
  88974. this.onBeforeRenderObservable = new BABYLON.Observable();
  88975. /**
  88976. * An event triggered after rendering the scene
  88977. * @type {BABYLON.Observable}
  88978. */
  88979. this.onAfterRenderObservable = new BABYLON.Observable();
  88980. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88981. this.isBackground = isBackground === undefined ? true : isBackground;
  88982. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88983. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88984. this._scene.layers.push(this);
  88985. var engine = this._scene.getEngine();
  88986. // VBO
  88987. var vertices = [];
  88988. vertices.push(1, 1);
  88989. vertices.push(-1, 1);
  88990. vertices.push(-1, -1);
  88991. vertices.push(1, -1);
  88992. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88993. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88994. this._createIndexBuffer();
  88995. // Effects
  88996. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88997. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88998. }
  88999. Object.defineProperty(Layer.prototype, "onDispose", {
  89000. set: function (callback) {
  89001. if (this._onDisposeObserver) {
  89002. this.onDisposeObservable.remove(this._onDisposeObserver);
  89003. }
  89004. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89005. },
  89006. enumerable: true,
  89007. configurable: true
  89008. });
  89009. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  89010. set: function (callback) {
  89011. if (this._onBeforeRenderObserver) {
  89012. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  89013. }
  89014. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  89015. },
  89016. enumerable: true,
  89017. configurable: true
  89018. });
  89019. Object.defineProperty(Layer.prototype, "onAfterRender", {
  89020. set: function (callback) {
  89021. if (this._onAfterRenderObserver) {
  89022. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89023. }
  89024. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  89025. },
  89026. enumerable: true,
  89027. configurable: true
  89028. });
  89029. Layer.prototype._createIndexBuffer = function () {
  89030. var engine = this._scene.getEngine();
  89031. // Indices
  89032. var indices = [];
  89033. indices.push(0);
  89034. indices.push(1);
  89035. indices.push(2);
  89036. indices.push(0);
  89037. indices.push(2);
  89038. indices.push(3);
  89039. this._indexBuffer = engine.createIndexBuffer(indices);
  89040. };
  89041. Layer.prototype._rebuild = function () {
  89042. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89043. if (vb) {
  89044. vb._rebuild();
  89045. }
  89046. this._createIndexBuffer();
  89047. };
  89048. Layer.prototype.render = function () {
  89049. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  89050. // Check
  89051. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  89052. return;
  89053. var engine = this._scene.getEngine();
  89054. this.onBeforeRenderObservable.notifyObservers(this);
  89055. // Render
  89056. engine.enableEffect(currentEffect);
  89057. engine.setState(false);
  89058. // Texture
  89059. currentEffect.setTexture("textureSampler", this.texture);
  89060. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  89061. // Color
  89062. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  89063. // Scale / offset
  89064. currentEffect.setVector2("offset", this.offset);
  89065. currentEffect.setVector2("scale", this.scale);
  89066. // VBOs
  89067. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89068. // Draw order
  89069. if (!this.alphaTest) {
  89070. engine.setAlphaMode(this.alphaBlendingMode);
  89071. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89072. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89073. }
  89074. else {
  89075. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89076. }
  89077. this.onAfterRenderObservable.notifyObservers(this);
  89078. };
  89079. Layer.prototype.dispose = function () {
  89080. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89081. if (vertexBuffer) {
  89082. vertexBuffer.dispose();
  89083. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89084. }
  89085. if (this._indexBuffer) {
  89086. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89087. this._indexBuffer = null;
  89088. }
  89089. if (this.texture) {
  89090. this.texture.dispose();
  89091. this.texture = null;
  89092. }
  89093. // Remove from scene
  89094. var index = this._scene.layers.indexOf(this);
  89095. this._scene.layers.splice(index, 1);
  89096. // Callback
  89097. this.onDisposeObservable.notifyObservers(this);
  89098. this.onDisposeObservable.clear();
  89099. this.onAfterRenderObservable.clear();
  89100. this.onBeforeRenderObservable.clear();
  89101. };
  89102. return Layer;
  89103. }());
  89104. BABYLON.Layer = Layer;
  89105. })(BABYLON || (BABYLON = {}));
  89106. //# sourceMappingURL=babylon.layer.js.map
  89107. "use strict";
  89108. var BABYLON;
  89109. (function (BABYLON) {
  89110. var TextureTools = /** @class */ (function () {
  89111. function TextureTools() {
  89112. }
  89113. /**
  89114. * Uses the GPU to create a copy texture rescaled at a given size
  89115. * @param texture Texture to copy from
  89116. * @param width Desired width
  89117. * @param height Desired height
  89118. * @return Generated texture
  89119. */
  89120. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  89121. if (useBilinearMode === void 0) { useBilinearMode = true; }
  89122. var scene = texture.getScene();
  89123. var engine = scene.getEngine();
  89124. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  89125. rtt.wrapU = texture.wrapU;
  89126. rtt.wrapV = texture.wrapV;
  89127. rtt.uOffset = texture.uOffset;
  89128. rtt.vOffset = texture.vOffset;
  89129. rtt.uScale = texture.uScale;
  89130. rtt.vScale = texture.vScale;
  89131. rtt.uAng = texture.uAng;
  89132. rtt.vAng = texture.vAng;
  89133. rtt.wAng = texture.wAng;
  89134. rtt.coordinatesIndex = texture.coordinatesIndex;
  89135. rtt.level = texture.level;
  89136. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  89137. rtt._texture.isReady = false;
  89138. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89139. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89140. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89141. passPostProcess.getEffect().executeWhenCompiled(function () {
  89142. passPostProcess.onApply = function (effect) {
  89143. effect.setTexture("textureSampler", texture);
  89144. };
  89145. var internalTexture = rtt.getInternalTexture();
  89146. if (internalTexture) {
  89147. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  89148. engine.unBindFramebuffer(internalTexture);
  89149. rtt.disposeFramebufferObjects();
  89150. passPostProcess.dispose();
  89151. internalTexture.isReady = true;
  89152. }
  89153. });
  89154. return rtt;
  89155. };
  89156. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  89157. if (!scene._environmentBRDFTexture) {
  89158. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89159. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89160. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89161. scene._environmentBRDFTexture = texture;
  89162. }
  89163. return scene._environmentBRDFTexture;
  89164. };
  89165. 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=";
  89166. return TextureTools;
  89167. }());
  89168. BABYLON.TextureTools = TextureTools;
  89169. })(BABYLON || (BABYLON = {}));
  89170. //# sourceMappingURL=babylon.textureTools.js.map
  89171. "use strict";
  89172. var BABYLON;
  89173. (function (BABYLON) {
  89174. var FramingBehavior = /** @class */ (function () {
  89175. function FramingBehavior() {
  89176. this._mode = FramingBehavior.FitFrustumSidesMode;
  89177. this._radiusScale = 1.0;
  89178. this._positionScale = 0.5;
  89179. this._defaultElevation = 0.3;
  89180. this._elevationReturnTime = 1500;
  89181. this._elevationReturnWaitTime = 1000;
  89182. this._zoomStopsAnimation = false;
  89183. this._framingTime = 1500;
  89184. this._isPointerDown = false;
  89185. this._lastInteractionTime = -Infinity;
  89186. // Framing control
  89187. this._animatables = new Array();
  89188. this._betaIsAnimating = false;
  89189. }
  89190. Object.defineProperty(FramingBehavior.prototype, "name", {
  89191. get: function () {
  89192. return "Framing";
  89193. },
  89194. enumerable: true,
  89195. configurable: true
  89196. });
  89197. Object.defineProperty(FramingBehavior.prototype, "mode", {
  89198. /**
  89199. * Gets current mode used by the behavior.
  89200. */
  89201. get: function () {
  89202. return this._mode;
  89203. },
  89204. /**
  89205. * Sets the current mode used by the behavior
  89206. */
  89207. set: function (mode) {
  89208. this._mode = mode;
  89209. },
  89210. enumerable: true,
  89211. configurable: true
  89212. });
  89213. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  89214. /**
  89215. * Gets the scale applied to the radius
  89216. */
  89217. get: function () {
  89218. return this._radiusScale;
  89219. },
  89220. /**
  89221. * Sets the scale applied to the radius (1 by default)
  89222. */
  89223. set: function (radius) {
  89224. this._radiusScale = radius;
  89225. },
  89226. enumerable: true,
  89227. configurable: true
  89228. });
  89229. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  89230. /**
  89231. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89232. */
  89233. get: function () {
  89234. return this._positionScale;
  89235. },
  89236. /**
  89237. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89238. */
  89239. set: function (scale) {
  89240. this._positionScale = scale;
  89241. },
  89242. enumerable: true,
  89243. configurable: true
  89244. });
  89245. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  89246. /**
  89247. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89248. * behaviour is triggered, in radians.
  89249. */
  89250. get: function () {
  89251. return this._defaultElevation;
  89252. },
  89253. /**
  89254. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89255. * behaviour is triggered, in radians.
  89256. */
  89257. set: function (elevation) {
  89258. this._defaultElevation = elevation;
  89259. },
  89260. enumerable: true,
  89261. configurable: true
  89262. });
  89263. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  89264. /**
  89265. * Gets the time (in milliseconds) taken to return to the default beta position.
  89266. * Negative value indicates camera should not return to default.
  89267. */
  89268. get: function () {
  89269. return this._elevationReturnTime;
  89270. },
  89271. /**
  89272. * Sets the time (in milliseconds) taken to return to the default beta position.
  89273. * Negative value indicates camera should not return to default.
  89274. */
  89275. set: function (speed) {
  89276. this._elevationReturnTime = speed;
  89277. },
  89278. enumerable: true,
  89279. configurable: true
  89280. });
  89281. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  89282. /**
  89283. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89284. */
  89285. get: function () {
  89286. return this._elevationReturnWaitTime;
  89287. },
  89288. /**
  89289. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89290. */
  89291. set: function (time) {
  89292. this._elevationReturnWaitTime = time;
  89293. },
  89294. enumerable: true,
  89295. configurable: true
  89296. });
  89297. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  89298. /**
  89299. * Gets the flag that indicates if user zooming should stop animation.
  89300. */
  89301. get: function () {
  89302. return this._zoomStopsAnimation;
  89303. },
  89304. /**
  89305. * Sets the flag that indicates if user zooming should stop animation.
  89306. */
  89307. set: function (flag) {
  89308. this._zoomStopsAnimation = flag;
  89309. },
  89310. enumerable: true,
  89311. configurable: true
  89312. });
  89313. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  89314. /**
  89315. * Gets the transition time when framing the mesh, in milliseconds
  89316. */
  89317. get: function () {
  89318. return this._framingTime;
  89319. },
  89320. /**
  89321. * Sets the transition time when framing the mesh, in milliseconds
  89322. */
  89323. set: function (time) {
  89324. this._framingTime = time;
  89325. },
  89326. enumerable: true,
  89327. configurable: true
  89328. });
  89329. FramingBehavior.prototype.init = function () {
  89330. // Do notihng
  89331. };
  89332. FramingBehavior.prototype.attach = function (camera) {
  89333. var _this = this;
  89334. this._attachedCamera = camera;
  89335. var scene = this._attachedCamera.getScene();
  89336. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89337. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89338. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89339. _this._isPointerDown = true;
  89340. return;
  89341. }
  89342. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89343. _this._isPointerDown = false;
  89344. }
  89345. });
  89346. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89347. if (mesh) {
  89348. _this.zoomOnMesh(mesh);
  89349. }
  89350. });
  89351. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89352. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89353. _this._applyUserInteraction();
  89354. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89355. // back to the default position after a given timeout
  89356. _this._maintainCameraAboveGround();
  89357. });
  89358. };
  89359. FramingBehavior.prototype.detach = function () {
  89360. if (!this._attachedCamera) {
  89361. return;
  89362. }
  89363. var scene = this._attachedCamera.getScene();
  89364. if (this._onPrePointerObservableObserver) {
  89365. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89366. }
  89367. if (this._onAfterCheckInputsObserver) {
  89368. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89369. }
  89370. if (this._onMeshTargetChangedObserver) {
  89371. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89372. }
  89373. this._attachedCamera = null;
  89374. };
  89375. /**
  89376. * Targets the given mesh and updates zoom level accordingly.
  89377. * @param mesh The mesh to target.
  89378. * @param radius Optional. If a cached radius position already exists, overrides default.
  89379. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89380. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89381. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89382. */
  89383. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89384. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89385. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89386. mesh.computeWorldMatrix(true);
  89387. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89388. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89389. };
  89390. /**
  89391. * Targets the given mesh with its children and updates zoom level accordingly.
  89392. * @param mesh The mesh to target.
  89393. * @param radius Optional. If a cached radius position already exists, overrides default.
  89394. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89395. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89396. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89397. */
  89398. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89399. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89400. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89401. mesh.computeWorldMatrix(true);
  89402. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89403. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89404. };
  89405. /**
  89406. * Targets the given meshes with their children and updates zoom level accordingly.
  89407. * @param meshes The mesh to target.
  89408. * @param radius Optional. If a cached radius position already exists, overrides default.
  89409. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89410. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89411. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89412. */
  89413. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89414. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89415. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89416. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89417. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89418. for (var i = 0; i < meshes.length; i++) {
  89419. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89420. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89421. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89422. }
  89423. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89424. };
  89425. /**
  89426. * Targets the given mesh and updates zoom level accordingly.
  89427. * @param mesh The mesh to target.
  89428. * @param radius Optional. If a cached radius position already exists, overrides default.
  89429. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89430. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89431. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89432. */
  89433. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89434. var _this = this;
  89435. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89436. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89437. var zoomTarget;
  89438. if (!this._attachedCamera) {
  89439. return;
  89440. }
  89441. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89442. var bottom = minimumWorld.y;
  89443. var top = maximumWorld.y;
  89444. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89445. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89446. if (focusOnOriginXZ) {
  89447. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89448. }
  89449. else {
  89450. var centerWorld = minimumWorld.add(radiusWorld);
  89451. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89452. }
  89453. if (!this._vectorTransition) {
  89454. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89455. }
  89456. this._betaIsAnimating = true;
  89457. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89458. if (animatable) {
  89459. this._animatables.push(animatable);
  89460. }
  89461. // sets the radius and lower radius bounds
  89462. // Small delta ensures camera is not always at lower zoom limit.
  89463. var radius = 0;
  89464. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89465. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89466. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89467. radius = position;
  89468. }
  89469. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89470. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89471. if (this._attachedCamera.lowerRadiusLimit === null) {
  89472. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89473. }
  89474. }
  89475. // Set sensibilities
  89476. var extend = maximumWorld.subtract(minimumWorld).length();
  89477. this._attachedCamera.panningSensibility = 5000 / extend;
  89478. this._attachedCamera.wheelPrecision = 100 / radius;
  89479. // transition to new radius
  89480. if (!this._radiusTransition) {
  89481. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89482. }
  89483. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89484. _this.stopAllAnimations();
  89485. if (onAnimationEnd) {
  89486. onAnimationEnd();
  89487. }
  89488. if (_this._attachedCamera) {
  89489. _this._attachedCamera.storeState();
  89490. }
  89491. });
  89492. if (animatable) {
  89493. this._animatables.push(animatable);
  89494. }
  89495. };
  89496. /**
  89497. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89498. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89499. * frustum width.
  89500. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89501. * to fully enclose the mesh in the viewing frustum.
  89502. */
  89503. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89504. var size = maximumWorld.subtract(minimumWorld);
  89505. var boxVectorGlobalDiagonal = size.length();
  89506. var frustumSlope = this._getFrustumSlope();
  89507. // Formula for setting distance
  89508. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89509. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89510. // Horizon distance
  89511. var radius = radiusWithoutFraming * this._radiusScale;
  89512. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89513. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89514. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89515. var camera = this._attachedCamera;
  89516. if (!camera) {
  89517. return 0;
  89518. }
  89519. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89520. // Don't exceed the requested limit
  89521. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89522. }
  89523. // Don't exceed the upper radius limit
  89524. if (camera.upperRadiusLimit) {
  89525. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89526. }
  89527. return distance;
  89528. };
  89529. /**
  89530. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89531. * is automatically returned to its default position (expected to be above ground plane).
  89532. */
  89533. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89534. var _this = this;
  89535. if (this._elevationReturnTime < 0) {
  89536. return;
  89537. }
  89538. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89539. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89540. var limitBeta = Math.PI * 0.5;
  89541. // Bring the camera back up if below the ground plane
  89542. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89543. this._betaIsAnimating = true;
  89544. //Transition to new position
  89545. this.stopAllAnimations();
  89546. if (!this._betaTransition) {
  89547. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89548. }
  89549. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89550. _this._clearAnimationLocks();
  89551. _this.stopAllAnimations();
  89552. });
  89553. if (animatabe) {
  89554. this._animatables.push(animatabe);
  89555. }
  89556. }
  89557. };
  89558. /**
  89559. * Returns the frustum slope based on the canvas ratio and camera FOV
  89560. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89561. */
  89562. FramingBehavior.prototype._getFrustumSlope = function () {
  89563. // Calculate the viewport ratio
  89564. // Aspect Ratio is Height/Width.
  89565. var camera = this._attachedCamera;
  89566. if (!camera) {
  89567. return BABYLON.Vector2.Zero();
  89568. }
  89569. var engine = camera.getScene().getEngine();
  89570. var aspectRatio = engine.getAspectRatio(camera);
  89571. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89572. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89573. var frustumSlopeY = Math.tan(camera.fov / 2);
  89574. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89575. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89576. // along the forward vector.
  89577. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89578. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89579. };
  89580. /**
  89581. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89582. */
  89583. FramingBehavior.prototype._clearAnimationLocks = function () {
  89584. this._betaIsAnimating = false;
  89585. };
  89586. /**
  89587. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89588. */
  89589. FramingBehavior.prototype._applyUserInteraction = function () {
  89590. if (this.isUserIsMoving) {
  89591. this._lastInteractionTime = BABYLON.Tools.Now;
  89592. this.stopAllAnimations();
  89593. this._clearAnimationLocks();
  89594. }
  89595. };
  89596. /**
  89597. * Stops and removes all animations that have been applied to the camera
  89598. */
  89599. FramingBehavior.prototype.stopAllAnimations = function () {
  89600. if (this._attachedCamera) {
  89601. this._attachedCamera.animations = [];
  89602. }
  89603. while (this._animatables.length) {
  89604. if (this._animatables[0]) {
  89605. this._animatables[0].onAnimationEnd = null;
  89606. this._animatables[0].stop();
  89607. }
  89608. this._animatables.shift();
  89609. }
  89610. };
  89611. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89612. /**
  89613. * Gets a value indicating if the user is moving the camera
  89614. */
  89615. get: function () {
  89616. if (!this._attachedCamera) {
  89617. return false;
  89618. }
  89619. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89620. this._attachedCamera.inertialBetaOffset !== 0 ||
  89621. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89622. this._attachedCamera.inertialPanningX !== 0 ||
  89623. this._attachedCamera.inertialPanningY !== 0 ||
  89624. this._isPointerDown;
  89625. },
  89626. enumerable: true,
  89627. configurable: true
  89628. });
  89629. /**
  89630. * The easing function used by animations
  89631. */
  89632. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89633. /**
  89634. * The easing mode used by animations
  89635. */
  89636. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89637. // Statics
  89638. /**
  89639. * The camera can move all the way towards the mesh.
  89640. */
  89641. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89642. /**
  89643. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89644. */
  89645. FramingBehavior.FitFrustumSidesMode = 1;
  89646. return FramingBehavior;
  89647. }());
  89648. BABYLON.FramingBehavior = FramingBehavior;
  89649. })(BABYLON || (BABYLON = {}));
  89650. //# sourceMappingURL=babylon.framingBehavior.js.map
  89651. "use strict";
  89652. var BABYLON;
  89653. (function (BABYLON) {
  89654. /**
  89655. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89656. */
  89657. var BouncingBehavior = /** @class */ (function () {
  89658. function BouncingBehavior() {
  89659. /**
  89660. * The duration of the animation, in milliseconds
  89661. */
  89662. this.transitionDuration = 450;
  89663. /**
  89664. * Length of the distance animated by the transition when lower radius is reached
  89665. */
  89666. this.lowerRadiusTransitionRange = 2;
  89667. /**
  89668. * Length of the distance animated by the transition when upper radius is reached
  89669. */
  89670. this.upperRadiusTransitionRange = -2;
  89671. this._autoTransitionRange = false;
  89672. // Animations
  89673. this._radiusIsAnimating = false;
  89674. this._radiusBounceTransition = null;
  89675. this._animatables = new Array();
  89676. }
  89677. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89678. get: function () {
  89679. return "Bouncing";
  89680. },
  89681. enumerable: true,
  89682. configurable: true
  89683. });
  89684. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89685. /**
  89686. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89687. */
  89688. get: function () {
  89689. return this._autoTransitionRange;
  89690. },
  89691. /**
  89692. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89693. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89694. */
  89695. set: function (value) {
  89696. var _this = this;
  89697. if (this._autoTransitionRange === value) {
  89698. return;
  89699. }
  89700. this._autoTransitionRange = value;
  89701. var camera = this._attachedCamera;
  89702. if (!camera) {
  89703. return;
  89704. }
  89705. if (value) {
  89706. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89707. if (!mesh) {
  89708. return;
  89709. }
  89710. mesh.computeWorldMatrix(true);
  89711. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89712. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89713. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89714. });
  89715. }
  89716. else if (this._onMeshTargetChangedObserver) {
  89717. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89718. }
  89719. },
  89720. enumerable: true,
  89721. configurable: true
  89722. });
  89723. BouncingBehavior.prototype.init = function () {
  89724. // Do notihng
  89725. };
  89726. BouncingBehavior.prototype.attach = function (camera) {
  89727. var _this = this;
  89728. this._attachedCamera = camera;
  89729. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89730. if (!_this._attachedCamera) {
  89731. return;
  89732. }
  89733. // Add the bounce animation to the lower radius limit
  89734. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89735. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89736. }
  89737. // Add the bounce animation to the upper radius limit
  89738. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89739. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89740. }
  89741. });
  89742. };
  89743. BouncingBehavior.prototype.detach = function () {
  89744. if (!this._attachedCamera) {
  89745. return;
  89746. }
  89747. if (this._onAfterCheckInputsObserver) {
  89748. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89749. }
  89750. if (this._onMeshTargetChangedObserver) {
  89751. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89752. }
  89753. this._attachedCamera = null;
  89754. };
  89755. /**
  89756. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89757. * @param radiusLimit The limit to check against.
  89758. * @return Bool to indicate if at limit.
  89759. */
  89760. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89761. if (!this._attachedCamera) {
  89762. return false;
  89763. }
  89764. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89765. return true;
  89766. }
  89767. return false;
  89768. };
  89769. /**
  89770. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89771. * @param radiusDelta The delta by which to animate to. Can be negative.
  89772. */
  89773. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89774. var _this = this;
  89775. if (!this._attachedCamera) {
  89776. return;
  89777. }
  89778. if (!this._radiusBounceTransition) {
  89779. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89780. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89781. }
  89782. // Prevent zoom until bounce has completed
  89783. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89784. this._attachedCamera.wheelPrecision = Infinity;
  89785. this._attachedCamera.inertialRadiusOffset = 0;
  89786. // Animate to the radius limit
  89787. this.stopAllAnimations();
  89788. this._radiusIsAnimating = true;
  89789. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89790. if (animatable) {
  89791. this._animatables.push(animatable);
  89792. }
  89793. };
  89794. /**
  89795. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89796. */
  89797. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89798. this._radiusIsAnimating = false;
  89799. if (this._attachedCamera) {
  89800. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89801. }
  89802. };
  89803. /**
  89804. * Stops and removes all animations that have been applied to the camera
  89805. */
  89806. BouncingBehavior.prototype.stopAllAnimations = function () {
  89807. if (this._attachedCamera) {
  89808. this._attachedCamera.animations = [];
  89809. }
  89810. while (this._animatables.length) {
  89811. this._animatables[0].onAnimationEnd = null;
  89812. this._animatables[0].stop();
  89813. this._animatables.shift();
  89814. }
  89815. };
  89816. /**
  89817. * The easing function used by animations
  89818. */
  89819. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89820. /**
  89821. * The easing mode used by animations
  89822. */
  89823. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89824. return BouncingBehavior;
  89825. }());
  89826. BABYLON.BouncingBehavior = BouncingBehavior;
  89827. })(BABYLON || (BABYLON = {}));
  89828. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89829. "use strict";
  89830. var BABYLON;
  89831. (function (BABYLON) {
  89832. var AutoRotationBehavior = /** @class */ (function () {
  89833. function AutoRotationBehavior() {
  89834. this._zoomStopsAnimation = false;
  89835. this._idleRotationSpeed = 0.05;
  89836. this._idleRotationWaitTime = 2000;
  89837. this._idleRotationSpinupTime = 2000;
  89838. this._isPointerDown = false;
  89839. this._lastFrameTime = null;
  89840. this._lastInteractionTime = -Infinity;
  89841. this._cameraRotationSpeed = 0;
  89842. this._lastFrameRadius = 0;
  89843. }
  89844. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89845. get: function () {
  89846. return "AutoRotation";
  89847. },
  89848. enumerable: true,
  89849. configurable: true
  89850. });
  89851. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89852. /**
  89853. * Gets the flag that indicates if user zooming should stop animation.
  89854. */
  89855. get: function () {
  89856. return this._zoomStopsAnimation;
  89857. },
  89858. /**
  89859. * Sets the flag that indicates if user zooming should stop animation.
  89860. */
  89861. set: function (flag) {
  89862. this._zoomStopsAnimation = flag;
  89863. },
  89864. enumerable: true,
  89865. configurable: true
  89866. });
  89867. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89868. /**
  89869. * Gets the default speed at which the camera rotates around the model.
  89870. */
  89871. get: function () {
  89872. return this._idleRotationSpeed;
  89873. },
  89874. /**
  89875. * Sets the default speed at which the camera rotates around the model.
  89876. */
  89877. set: function (speed) {
  89878. this._idleRotationSpeed = speed;
  89879. },
  89880. enumerable: true,
  89881. configurable: true
  89882. });
  89883. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89884. /**
  89885. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89886. */
  89887. get: function () {
  89888. return this._idleRotationWaitTime;
  89889. },
  89890. /**
  89891. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89892. */
  89893. set: function (time) {
  89894. this._idleRotationWaitTime = time;
  89895. },
  89896. enumerable: true,
  89897. configurable: true
  89898. });
  89899. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89900. /**
  89901. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89902. */
  89903. get: function () {
  89904. return this._idleRotationSpinupTime;
  89905. },
  89906. /**
  89907. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89908. */
  89909. set: function (time) {
  89910. this._idleRotationSpinupTime = time;
  89911. },
  89912. enumerable: true,
  89913. configurable: true
  89914. });
  89915. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89916. /**
  89917. * Gets a value indicating if the camera is currently rotating because of this behavior
  89918. */
  89919. get: function () {
  89920. return Math.abs(this._cameraRotationSpeed) > 0;
  89921. },
  89922. enumerable: true,
  89923. configurable: true
  89924. });
  89925. AutoRotationBehavior.prototype.init = function () {
  89926. // Do notihng
  89927. };
  89928. AutoRotationBehavior.prototype.attach = function (camera) {
  89929. var _this = this;
  89930. this._attachedCamera = camera;
  89931. var scene = this._attachedCamera.getScene();
  89932. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89933. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89934. _this._isPointerDown = true;
  89935. return;
  89936. }
  89937. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89938. _this._isPointerDown = false;
  89939. }
  89940. });
  89941. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89942. var now = BABYLON.Tools.Now;
  89943. var dt = 0;
  89944. if (_this._lastFrameTime != null) {
  89945. dt = now - _this._lastFrameTime;
  89946. }
  89947. _this._lastFrameTime = now;
  89948. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89949. _this._applyUserInteraction();
  89950. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89951. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89952. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89953. // Step camera rotation by rotation speed
  89954. if (_this._attachedCamera) {
  89955. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89956. }
  89957. });
  89958. };
  89959. AutoRotationBehavior.prototype.detach = function () {
  89960. if (!this._attachedCamera) {
  89961. return;
  89962. }
  89963. var scene = this._attachedCamera.getScene();
  89964. if (this._onPrePointerObservableObserver) {
  89965. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89966. }
  89967. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89968. this._attachedCamera = null;
  89969. };
  89970. /**
  89971. * Returns true if user is scrolling.
  89972. * @return true if user is scrolling.
  89973. */
  89974. AutoRotationBehavior.prototype._userIsZooming = function () {
  89975. if (!this._attachedCamera) {
  89976. return false;
  89977. }
  89978. return this._attachedCamera.inertialRadiusOffset !== 0;
  89979. };
  89980. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89981. if (!this._attachedCamera) {
  89982. return false;
  89983. }
  89984. var zoomHasHitLimit = false;
  89985. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89986. zoomHasHitLimit = true;
  89987. }
  89988. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89989. this._lastFrameRadius = this._attachedCamera.radius;
  89990. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89991. };
  89992. /**
  89993. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89994. */
  89995. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89996. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89997. this._lastInteractionTime = BABYLON.Tools.Now;
  89998. }
  89999. };
  90000. // Tools
  90001. AutoRotationBehavior.prototype._userIsMoving = function () {
  90002. if (!this._attachedCamera) {
  90003. return false;
  90004. }
  90005. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  90006. this._attachedCamera.inertialBetaOffset !== 0 ||
  90007. this._attachedCamera.inertialRadiusOffset !== 0 ||
  90008. this._attachedCamera.inertialPanningX !== 0 ||
  90009. this._attachedCamera.inertialPanningY !== 0 ||
  90010. this._isPointerDown;
  90011. };
  90012. return AutoRotationBehavior;
  90013. }());
  90014. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  90015. })(BABYLON || (BABYLON = {}));
  90016. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  90017. "use strict";
  90018. var BABYLON;
  90019. (function (BABYLON) {
  90020. var NullEngineOptions = /** @class */ (function () {
  90021. function NullEngineOptions() {
  90022. this.renderWidth = 512;
  90023. this.renderHeight = 256;
  90024. this.textureSize = 512;
  90025. this.deterministicLockstep = false;
  90026. this.lockstepMaxSteps = 4;
  90027. }
  90028. return NullEngineOptions;
  90029. }());
  90030. BABYLON.NullEngineOptions = NullEngineOptions;
  90031. /**
  90032. * The null engine class provides support for headless version of babylon.js.
  90033. * This can be used in server side scenario or for testing purposes
  90034. */
  90035. var NullEngine = /** @class */ (function (_super) {
  90036. __extends(NullEngine, _super);
  90037. function NullEngine(options) {
  90038. if (options === void 0) { options = new NullEngineOptions(); }
  90039. var _this = _super.call(this, null) || this;
  90040. if (options.deterministicLockstep === undefined) {
  90041. options.deterministicLockstep = false;
  90042. }
  90043. if (options.lockstepMaxSteps === undefined) {
  90044. options.lockstepMaxSteps = 4;
  90045. }
  90046. _this._options = options;
  90047. // Init caps
  90048. // We consider we are on a webgl1 capable device
  90049. _this._caps = new BABYLON.EngineCapabilities();
  90050. _this._caps.maxTexturesImageUnits = 16;
  90051. _this._caps.maxVertexTextureImageUnits = 16;
  90052. _this._caps.maxTextureSize = 512;
  90053. _this._caps.maxCubemapTextureSize = 512;
  90054. _this._caps.maxRenderTextureSize = 512;
  90055. _this._caps.maxVertexAttribs = 16;
  90056. _this._caps.maxVaryingVectors = 16;
  90057. _this._caps.maxFragmentUniformVectors = 16;
  90058. _this._caps.maxVertexUniformVectors = 16;
  90059. // Extensions
  90060. _this._caps.standardDerivatives = false;
  90061. _this._caps.astc = null;
  90062. _this._caps.s3tc = null;
  90063. _this._caps.pvrtc = null;
  90064. _this._caps.etc1 = null;
  90065. _this._caps.etc2 = null;
  90066. _this._caps.textureAnisotropicFilterExtension = null;
  90067. _this._caps.maxAnisotropy = 0;
  90068. _this._caps.uintIndices = false;
  90069. _this._caps.fragmentDepthSupported = false;
  90070. _this._caps.highPrecisionShaderSupported = true;
  90071. _this._caps.colorBufferFloat = false;
  90072. _this._caps.textureFloat = false;
  90073. _this._caps.textureFloatLinearFiltering = false;
  90074. _this._caps.textureFloatRender = false;
  90075. _this._caps.textureHalfFloat = false;
  90076. _this._caps.textureHalfFloatLinearFiltering = false;
  90077. _this._caps.textureHalfFloatRender = false;
  90078. _this._caps.textureLOD = false;
  90079. _this._caps.drawBuffersExtension = false;
  90080. _this._caps.depthTextureExtension = false;
  90081. _this._caps.vertexArrayObject = false;
  90082. _this._caps.instancedArrays = false;
  90083. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  90084. // Wrappers
  90085. if (typeof URL === "undefined") {
  90086. URL = {
  90087. createObjectURL: function () { },
  90088. revokeObjectURL: function () { }
  90089. };
  90090. }
  90091. if (typeof Blob === "undefined") {
  90092. Blob = function () { };
  90093. }
  90094. return _this;
  90095. }
  90096. NullEngine.prototype.isDeterministicLockStep = function () {
  90097. return this._options.deterministicLockstep;
  90098. };
  90099. NullEngine.prototype.getLockstepMaxSteps = function () {
  90100. return this._options.lockstepMaxSteps;
  90101. };
  90102. NullEngine.prototype.getHardwareScalingLevel = function () {
  90103. return 1.0;
  90104. };
  90105. NullEngine.prototype.createVertexBuffer = function (vertices) {
  90106. return {
  90107. capacity: 0,
  90108. references: 1,
  90109. is32Bits: false
  90110. };
  90111. };
  90112. NullEngine.prototype.createIndexBuffer = function (indices) {
  90113. return {
  90114. capacity: 0,
  90115. references: 1,
  90116. is32Bits: false
  90117. };
  90118. };
  90119. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  90120. if (stencil === void 0) { stencil = false; }
  90121. };
  90122. NullEngine.prototype.getRenderWidth = function (useScreen) {
  90123. if (useScreen === void 0) { useScreen = false; }
  90124. if (!useScreen && this._currentRenderTarget) {
  90125. return this._currentRenderTarget.width;
  90126. }
  90127. return this._options.renderWidth;
  90128. };
  90129. NullEngine.prototype.getRenderHeight = function (useScreen) {
  90130. if (useScreen === void 0) { useScreen = false; }
  90131. if (!useScreen && this._currentRenderTarget) {
  90132. return this._currentRenderTarget.height;
  90133. }
  90134. return this._options.renderHeight;
  90135. };
  90136. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  90137. this._cachedViewport = viewport;
  90138. };
  90139. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  90140. return {
  90141. transformFeedback: null,
  90142. __SPECTOR_rebuildProgram: null
  90143. };
  90144. };
  90145. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  90146. return [];
  90147. };
  90148. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  90149. return [];
  90150. };
  90151. NullEngine.prototype.bindSamplers = function (effect) {
  90152. this._currentEffect = null;
  90153. };
  90154. NullEngine.prototype.enableEffect = function (effect) {
  90155. this._currentEffect = effect;
  90156. if (effect.onBind) {
  90157. effect.onBind(effect);
  90158. }
  90159. effect.onBindObservable.notifyObservers(effect);
  90160. };
  90161. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  90162. if (zOffset === void 0) { zOffset = 0; }
  90163. if (reverseSide === void 0) { reverseSide = false; }
  90164. };
  90165. NullEngine.prototype.setIntArray = function (uniform, array) {
  90166. };
  90167. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  90168. };
  90169. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  90170. };
  90171. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  90172. };
  90173. NullEngine.prototype.setFloatArray = function (uniform, array) {
  90174. };
  90175. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  90176. };
  90177. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  90178. };
  90179. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  90180. };
  90181. NullEngine.prototype.setArray = function (uniform, array) {
  90182. };
  90183. NullEngine.prototype.setArray2 = function (uniform, array) {
  90184. };
  90185. NullEngine.prototype.setArray3 = function (uniform, array) {
  90186. };
  90187. NullEngine.prototype.setArray4 = function (uniform, array) {
  90188. };
  90189. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  90190. };
  90191. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  90192. };
  90193. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  90194. };
  90195. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  90196. };
  90197. NullEngine.prototype.setFloat = function (uniform, value) {
  90198. };
  90199. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  90200. };
  90201. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  90202. };
  90203. NullEngine.prototype.setBool = function (uniform, bool) {
  90204. };
  90205. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  90206. };
  90207. NullEngine.prototype.setColor3 = function (uniform, color3) {
  90208. };
  90209. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  90210. };
  90211. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  90212. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  90213. if (this._alphaMode === mode) {
  90214. return;
  90215. }
  90216. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  90217. if (!noDepthWriteChange) {
  90218. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  90219. }
  90220. this._alphaMode = mode;
  90221. };
  90222. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  90223. };
  90224. NullEngine.prototype.wipeCaches = function (bruteForce) {
  90225. if (this.preventCacheWipeBetweenFrames) {
  90226. return;
  90227. }
  90228. this.resetTextureCache();
  90229. this._currentEffect = null;
  90230. if (bruteForce) {
  90231. this._currentProgram = null;
  90232. this._stencilState.reset();
  90233. this._depthCullingState.reset();
  90234. this._alphaState.reset();
  90235. }
  90236. this._cachedVertexBuffers = null;
  90237. this._cachedIndexBuffer = null;
  90238. this._cachedEffectForVertexBuffers = null;
  90239. };
  90240. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  90241. };
  90242. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  90243. };
  90244. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  90245. };
  90246. NullEngine.prototype._createTexture = function () {
  90247. return {};
  90248. };
  90249. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  90250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90251. if (onLoad === void 0) { onLoad = null; }
  90252. if (onError === void 0) { onError = null; }
  90253. if (buffer === void 0) { buffer = null; }
  90254. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  90255. var url = String(urlArg);
  90256. texture.url = url;
  90257. texture.generateMipMaps = !noMipmap;
  90258. texture.samplingMode = samplingMode;
  90259. texture.invertY = invertY;
  90260. texture.baseWidth = this._options.textureSize;
  90261. texture.baseHeight = this._options.textureSize;
  90262. texture.width = this._options.textureSize;
  90263. texture.height = this._options.textureSize;
  90264. if (format) {
  90265. texture.format = format;
  90266. }
  90267. texture.isReady = true;
  90268. if (onLoad) {
  90269. onLoad();
  90270. }
  90271. return texture;
  90272. };
  90273. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  90274. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  90275. if (options !== undefined && typeof options === "object") {
  90276. fullOptions.generateMipMaps = options.generateMipMaps;
  90277. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  90278. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  90279. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  90280. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  90281. }
  90282. else {
  90283. fullOptions.generateMipMaps = options;
  90284. fullOptions.generateDepthBuffer = true;
  90285. fullOptions.generateStencilBuffer = false;
  90286. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90287. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90288. }
  90289. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  90290. var width = size.width || size;
  90291. var height = size.height || size;
  90292. texture._depthStencilBuffer = {};
  90293. texture._framebuffer = {};
  90294. texture.baseWidth = width;
  90295. texture.baseHeight = height;
  90296. texture.width = width;
  90297. texture.height = height;
  90298. texture.isReady = true;
  90299. texture.samples = 1;
  90300. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  90301. texture.samplingMode = fullOptions.samplingMode;
  90302. texture.type = fullOptions.type;
  90303. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  90304. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  90305. return texture;
  90306. };
  90307. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  90308. texture.samplingMode = samplingMode;
  90309. };
  90310. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  90311. if (this._currentRenderTarget) {
  90312. this.unBindFramebuffer(this._currentRenderTarget);
  90313. }
  90314. this._currentRenderTarget = texture;
  90315. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  90316. if (this._cachedViewport && !forceFullscreenViewport) {
  90317. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  90318. }
  90319. };
  90320. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  90321. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  90322. this._currentRenderTarget = null;
  90323. if (onBeforeUnbind) {
  90324. if (texture._MSAAFramebuffer) {
  90325. this._currentFramebuffer = texture._framebuffer;
  90326. }
  90327. onBeforeUnbind();
  90328. }
  90329. this._currentFramebuffer = null;
  90330. };
  90331. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90332. var vbo = {
  90333. capacity: 1,
  90334. references: 1,
  90335. is32Bits: false
  90336. };
  90337. return vbo;
  90338. };
  90339. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90340. if (offset === void 0) { offset = 0; }
  90341. };
  90342. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90343. };
  90344. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90345. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90346. this._boundTexturesCache[this._activeChannel] = texture;
  90347. }
  90348. };
  90349. NullEngine.prototype._bindTexture = function (channel, texture) {
  90350. if (channel < 0) {
  90351. return;
  90352. }
  90353. this._bindTextureDirectly(0, texture);
  90354. };
  90355. NullEngine.prototype._releaseBuffer = function (buffer) {
  90356. buffer.references--;
  90357. if (buffer.references === 0) {
  90358. return true;
  90359. }
  90360. return false;
  90361. };
  90362. return NullEngine;
  90363. }(BABYLON.Engine));
  90364. BABYLON.NullEngine = NullEngine;
  90365. })(BABYLON || (BABYLON = {}));
  90366. //# sourceMappingURL=babylon.nullEngine.js.map
  90367. "use strict";
  90368. var BABYLON;
  90369. (function (BABYLON) {
  90370. /**
  90371. * This class can be used to get instrumentation data from a Babylon engine
  90372. */
  90373. var EngineInstrumentation = /** @class */ (function () {
  90374. function EngineInstrumentation(engine) {
  90375. this.engine = engine;
  90376. this._captureGPUFrameTime = false;
  90377. this._gpuFrameTime = new BABYLON.PerfCounter();
  90378. this._captureShaderCompilationTime = false;
  90379. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90380. // Observers
  90381. this._onBeginFrameObserver = null;
  90382. this._onEndFrameObserver = null;
  90383. this._onBeforeShaderCompilationObserver = null;
  90384. this._onAfterShaderCompilationObserver = null;
  90385. }
  90386. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90387. // Properties
  90388. /**
  90389. * Gets the perf counter used for GPU frame time
  90390. */
  90391. get: function () {
  90392. return this._gpuFrameTime;
  90393. },
  90394. enumerable: true,
  90395. configurable: true
  90396. });
  90397. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90398. /**
  90399. * Gets the GPU frame time capture status
  90400. */
  90401. get: function () {
  90402. return this._captureGPUFrameTime;
  90403. },
  90404. /**
  90405. * Enable or disable the GPU frame time capture
  90406. */
  90407. set: function (value) {
  90408. var _this = this;
  90409. if (value === this._captureGPUFrameTime) {
  90410. return;
  90411. }
  90412. this._captureGPUFrameTime = value;
  90413. if (value) {
  90414. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90415. if (!_this._gpuFrameTimeToken) {
  90416. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90417. }
  90418. });
  90419. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90420. if (!_this._gpuFrameTimeToken) {
  90421. return;
  90422. }
  90423. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90424. if (time > -1) {
  90425. _this._gpuFrameTimeToken = null;
  90426. _this._gpuFrameTime.fetchNewFrame();
  90427. _this._gpuFrameTime.addCount(time, true);
  90428. }
  90429. });
  90430. }
  90431. else {
  90432. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90433. this._onBeginFrameObserver = null;
  90434. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90435. this._onEndFrameObserver = null;
  90436. }
  90437. },
  90438. enumerable: true,
  90439. configurable: true
  90440. });
  90441. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90442. /**
  90443. * Gets the perf counter used for shader compilation time
  90444. */
  90445. get: function () {
  90446. return this._shaderCompilationTime;
  90447. },
  90448. enumerable: true,
  90449. configurable: true
  90450. });
  90451. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90452. /**
  90453. * Gets the shader compilation time capture status
  90454. */
  90455. get: function () {
  90456. return this._captureShaderCompilationTime;
  90457. },
  90458. /**
  90459. * Enable or disable the shader compilation time capture
  90460. */
  90461. set: function (value) {
  90462. var _this = this;
  90463. if (value === this._captureShaderCompilationTime) {
  90464. return;
  90465. }
  90466. this._captureShaderCompilationTime = value;
  90467. if (value) {
  90468. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90469. _this._shaderCompilationTime.fetchNewFrame();
  90470. _this._shaderCompilationTime.beginMonitoring();
  90471. });
  90472. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90473. _this._shaderCompilationTime.endMonitoring();
  90474. });
  90475. }
  90476. else {
  90477. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90478. this._onBeforeShaderCompilationObserver = null;
  90479. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90480. this._onAfterShaderCompilationObserver = null;
  90481. }
  90482. },
  90483. enumerable: true,
  90484. configurable: true
  90485. });
  90486. EngineInstrumentation.prototype.dispose = function () {
  90487. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90488. this._onBeginFrameObserver = null;
  90489. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90490. this._onEndFrameObserver = null;
  90491. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90492. this._onBeforeShaderCompilationObserver = null;
  90493. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90494. this._onAfterShaderCompilationObserver = null;
  90495. this.engine = null;
  90496. };
  90497. return EngineInstrumentation;
  90498. }());
  90499. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90500. })(BABYLON || (BABYLON = {}));
  90501. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90502. "use strict";
  90503. var BABYLON;
  90504. (function (BABYLON) {
  90505. /**
  90506. * This class can be used to get instrumentation data from a Babylon engine
  90507. */
  90508. var SceneInstrumentation = /** @class */ (function () {
  90509. function SceneInstrumentation(scene) {
  90510. var _this = this;
  90511. this.scene = scene;
  90512. this._captureActiveMeshesEvaluationTime = false;
  90513. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90514. this._captureRenderTargetsRenderTime = false;
  90515. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90516. this._captureFrameTime = false;
  90517. this._frameTime = new BABYLON.PerfCounter();
  90518. this._captureRenderTime = false;
  90519. this._renderTime = new BABYLON.PerfCounter();
  90520. this._captureInterFrameTime = false;
  90521. this._interFrameTime = new BABYLON.PerfCounter();
  90522. this._captureParticlesRenderTime = false;
  90523. this._particlesRenderTime = new BABYLON.PerfCounter();
  90524. this._captureSpritesRenderTime = false;
  90525. this._spritesRenderTime = new BABYLON.PerfCounter();
  90526. this._capturePhysicsTime = false;
  90527. this._physicsTime = new BABYLON.PerfCounter();
  90528. this._captureAnimationsTime = false;
  90529. this._animationsTime = new BABYLON.PerfCounter();
  90530. // Observers
  90531. this._onBeforeActiveMeshesEvaluationObserver = null;
  90532. this._onAfterActiveMeshesEvaluationObserver = null;
  90533. this._onBeforeRenderTargetsRenderObserver = null;
  90534. this._onAfterRenderTargetsRenderObserver = null;
  90535. this._onAfterRenderObserver = null;
  90536. this._onBeforeDrawPhaseObserver = null;
  90537. this._onAfterDrawPhaseObserver = null;
  90538. this._onBeforeAnimationsObserver = null;
  90539. this._onBeforeParticlesRenderingObserver = null;
  90540. this._onAfterParticlesRenderingObserver = null;
  90541. this._onBeforeSpritesRenderingObserver = null;
  90542. this._onAfterSpritesRenderingObserver = null;
  90543. this._onBeforePhysicsObserver = null;
  90544. this._onAfterPhysicsObserver = null;
  90545. this._onAfterAnimationsObserver = null;
  90546. // Before render
  90547. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90548. if (_this._captureActiveMeshesEvaluationTime) {
  90549. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90550. }
  90551. if (_this._captureRenderTargetsRenderTime) {
  90552. _this._renderTargetsRenderTime.fetchNewFrame();
  90553. }
  90554. if (_this._captureFrameTime) {
  90555. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90556. _this._frameTime.beginMonitoring();
  90557. }
  90558. if (_this._captureInterFrameTime) {
  90559. _this._interFrameTime.endMonitoring();
  90560. }
  90561. if (_this._captureParticlesRenderTime) {
  90562. _this._particlesRenderTime.fetchNewFrame();
  90563. }
  90564. if (_this._captureSpritesRenderTime) {
  90565. _this._spritesRenderTime.fetchNewFrame();
  90566. }
  90567. if (_this._captureAnimationsTime) {
  90568. _this._animationsTime.beginMonitoring();
  90569. }
  90570. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90571. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90572. });
  90573. // After render
  90574. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90575. if (_this._captureFrameTime) {
  90576. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90577. _this._frameTime.endMonitoring();
  90578. }
  90579. if (_this._captureRenderTime) {
  90580. _this._renderTime.endMonitoring(false);
  90581. }
  90582. if (_this._captureInterFrameTime) {
  90583. _this._interFrameTime.beginMonitoring();
  90584. }
  90585. });
  90586. }
  90587. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90588. // Properties
  90589. /**
  90590. * Gets the perf counter used for active meshes evaluation time
  90591. */
  90592. get: function () {
  90593. return this._activeMeshesEvaluationTime;
  90594. },
  90595. enumerable: true,
  90596. configurable: true
  90597. });
  90598. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90599. /**
  90600. * Gets the active meshes evaluation time capture status
  90601. */
  90602. get: function () {
  90603. return this._captureActiveMeshesEvaluationTime;
  90604. },
  90605. /**
  90606. * Enable or disable the active meshes evaluation time capture
  90607. */
  90608. set: function (value) {
  90609. var _this = this;
  90610. if (value === this._captureActiveMeshesEvaluationTime) {
  90611. return;
  90612. }
  90613. this._captureActiveMeshesEvaluationTime = value;
  90614. if (value) {
  90615. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90616. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90617. _this._activeMeshesEvaluationTime.beginMonitoring();
  90618. });
  90619. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90620. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90621. _this._activeMeshesEvaluationTime.endMonitoring();
  90622. });
  90623. }
  90624. else {
  90625. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90626. this._onBeforeActiveMeshesEvaluationObserver = null;
  90627. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90628. this._onAfterActiveMeshesEvaluationObserver = null;
  90629. }
  90630. },
  90631. enumerable: true,
  90632. configurable: true
  90633. });
  90634. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90635. /**
  90636. * Gets the perf counter used for render targets render time
  90637. */
  90638. get: function () {
  90639. return this._renderTargetsRenderTime;
  90640. },
  90641. enumerable: true,
  90642. configurable: true
  90643. });
  90644. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90645. /**
  90646. * Gets the render targets render time capture status
  90647. */
  90648. get: function () {
  90649. return this._captureRenderTargetsRenderTime;
  90650. },
  90651. /**
  90652. * Enable or disable the render targets render time capture
  90653. */
  90654. set: function (value) {
  90655. var _this = this;
  90656. if (value === this._captureRenderTargetsRenderTime) {
  90657. return;
  90658. }
  90659. this._captureRenderTargetsRenderTime = value;
  90660. if (value) {
  90661. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90662. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90663. _this._renderTargetsRenderTime.beginMonitoring();
  90664. });
  90665. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90666. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90667. _this._renderTargetsRenderTime.endMonitoring(false);
  90668. });
  90669. }
  90670. else {
  90671. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90672. this._onBeforeRenderTargetsRenderObserver = null;
  90673. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90674. this._onAfterRenderTargetsRenderObserver = null;
  90675. }
  90676. },
  90677. enumerable: true,
  90678. configurable: true
  90679. });
  90680. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90681. /**
  90682. * Gets the perf counter used for particles render time
  90683. */
  90684. get: function () {
  90685. return this._particlesRenderTime;
  90686. },
  90687. enumerable: true,
  90688. configurable: true
  90689. });
  90690. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90691. /**
  90692. * Gets the particles render time capture status
  90693. */
  90694. get: function () {
  90695. return this._captureParticlesRenderTime;
  90696. },
  90697. /**
  90698. * Enable or disable the particles render time capture
  90699. */
  90700. set: function (value) {
  90701. var _this = this;
  90702. if (value === this._captureParticlesRenderTime) {
  90703. return;
  90704. }
  90705. this._captureParticlesRenderTime = value;
  90706. if (value) {
  90707. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90708. BABYLON.Tools.StartPerformanceCounter("Particles");
  90709. _this._particlesRenderTime.beginMonitoring();
  90710. });
  90711. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90712. BABYLON.Tools.EndPerformanceCounter("Particles");
  90713. _this._particlesRenderTime.endMonitoring(false);
  90714. });
  90715. }
  90716. else {
  90717. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90718. this._onBeforeParticlesRenderingObserver = null;
  90719. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90720. this._onAfterParticlesRenderingObserver = null;
  90721. }
  90722. },
  90723. enumerable: true,
  90724. configurable: true
  90725. });
  90726. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90727. /**
  90728. * Gets the perf counter used for sprites render time
  90729. */
  90730. get: function () {
  90731. return this._spritesRenderTime;
  90732. },
  90733. enumerable: true,
  90734. configurable: true
  90735. });
  90736. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90737. /**
  90738. * Gets the sprites render time capture status
  90739. */
  90740. get: function () {
  90741. return this._captureSpritesRenderTime;
  90742. },
  90743. /**
  90744. * Enable or disable the sprites render time capture
  90745. */
  90746. set: function (value) {
  90747. var _this = this;
  90748. if (value === this._captureSpritesRenderTime) {
  90749. return;
  90750. }
  90751. this._captureSpritesRenderTime = value;
  90752. if (value) {
  90753. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90754. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90755. _this._spritesRenderTime.beginMonitoring();
  90756. });
  90757. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90758. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90759. _this._spritesRenderTime.endMonitoring(false);
  90760. });
  90761. }
  90762. else {
  90763. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90764. this._onBeforeSpritesRenderingObserver = null;
  90765. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90766. this._onAfterSpritesRenderingObserver = null;
  90767. }
  90768. },
  90769. enumerable: true,
  90770. configurable: true
  90771. });
  90772. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90773. /**
  90774. * Gets the perf counter used for physics time
  90775. */
  90776. get: function () {
  90777. return this._physicsTime;
  90778. },
  90779. enumerable: true,
  90780. configurable: true
  90781. });
  90782. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90783. /**
  90784. * Gets the physics time capture status
  90785. */
  90786. get: function () {
  90787. return this._capturePhysicsTime;
  90788. },
  90789. /**
  90790. * Enable or disable the physics time capture
  90791. */
  90792. set: function (value) {
  90793. var _this = this;
  90794. if (value === this._capturePhysicsTime) {
  90795. return;
  90796. }
  90797. this._capturePhysicsTime = value;
  90798. if (value) {
  90799. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90800. BABYLON.Tools.StartPerformanceCounter("Physics");
  90801. _this._physicsTime.beginMonitoring();
  90802. });
  90803. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90804. BABYLON.Tools.EndPerformanceCounter("Physics");
  90805. _this._physicsTime.endMonitoring();
  90806. });
  90807. }
  90808. else {
  90809. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90810. this._onBeforePhysicsObserver = null;
  90811. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90812. this._onAfterPhysicsObserver = null;
  90813. }
  90814. },
  90815. enumerable: true,
  90816. configurable: true
  90817. });
  90818. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90819. /**
  90820. * Gets the perf counter used for animations time
  90821. */
  90822. get: function () {
  90823. return this._animationsTime;
  90824. },
  90825. enumerable: true,
  90826. configurable: true
  90827. });
  90828. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90829. /**
  90830. * Gets the animations time capture status
  90831. */
  90832. get: function () {
  90833. return this._captureAnimationsTime;
  90834. },
  90835. /**
  90836. * Enable or disable the animations time capture
  90837. */
  90838. set: function (value) {
  90839. var _this = this;
  90840. if (value === this._captureAnimationsTime) {
  90841. return;
  90842. }
  90843. this._captureAnimationsTime = value;
  90844. if (value) {
  90845. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90846. _this._animationsTime.endMonitoring();
  90847. });
  90848. }
  90849. else {
  90850. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90851. this._onAfterAnimationsObserver = null;
  90852. }
  90853. },
  90854. enumerable: true,
  90855. configurable: true
  90856. });
  90857. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90858. /**
  90859. * Gets the perf counter used for frame time capture
  90860. */
  90861. get: function () {
  90862. return this._frameTime;
  90863. },
  90864. enumerable: true,
  90865. configurable: true
  90866. });
  90867. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90868. /**
  90869. * Gets the frame time capture status
  90870. */
  90871. get: function () {
  90872. return this._captureFrameTime;
  90873. },
  90874. /**
  90875. * Enable or disable the frame time capture
  90876. */
  90877. set: function (value) {
  90878. this._captureFrameTime = value;
  90879. },
  90880. enumerable: true,
  90881. configurable: true
  90882. });
  90883. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90884. /**
  90885. * Gets the perf counter used for inter-frames time capture
  90886. */
  90887. get: function () {
  90888. return this._interFrameTime;
  90889. },
  90890. enumerable: true,
  90891. configurable: true
  90892. });
  90893. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90894. /**
  90895. * Gets the inter-frames time capture status
  90896. */
  90897. get: function () {
  90898. return this._captureInterFrameTime;
  90899. },
  90900. /**
  90901. * Enable or disable the inter-frames time capture
  90902. */
  90903. set: function (value) {
  90904. this._captureInterFrameTime = value;
  90905. },
  90906. enumerable: true,
  90907. configurable: true
  90908. });
  90909. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90910. /**
  90911. * Gets the perf counter used for render time capture
  90912. */
  90913. get: function () {
  90914. return this._renderTime;
  90915. },
  90916. enumerable: true,
  90917. configurable: true
  90918. });
  90919. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90920. /**
  90921. * Gets the render time capture status
  90922. */
  90923. get: function () {
  90924. return this._captureRenderTime;
  90925. },
  90926. /**
  90927. * Enable or disable the render time capture
  90928. */
  90929. set: function (value) {
  90930. var _this = this;
  90931. if (value === this._captureRenderTime) {
  90932. return;
  90933. }
  90934. this._captureRenderTime = value;
  90935. if (value) {
  90936. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90937. _this._renderTime.beginMonitoring();
  90938. BABYLON.Tools.StartPerformanceCounter("Main render");
  90939. });
  90940. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90941. _this._renderTime.endMonitoring(false);
  90942. BABYLON.Tools.EndPerformanceCounter("Main render");
  90943. });
  90944. }
  90945. else {
  90946. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90947. this._onBeforeDrawPhaseObserver = null;
  90948. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90949. this._onAfterDrawPhaseObserver = null;
  90950. }
  90951. },
  90952. enumerable: true,
  90953. configurable: true
  90954. });
  90955. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90956. /**
  90957. * Gets the perf counter used for draw calls
  90958. */
  90959. get: function () {
  90960. return this.scene.getEngine()._drawCalls;
  90961. },
  90962. enumerable: true,
  90963. configurable: true
  90964. });
  90965. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90966. /**
  90967. * Gets the perf counter used for texture collisions
  90968. */
  90969. get: function () {
  90970. return this.scene.getEngine()._textureCollisions;
  90971. },
  90972. enumerable: true,
  90973. configurable: true
  90974. });
  90975. SceneInstrumentation.prototype.dispose = function () {
  90976. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90977. this._onAfterRenderObserver = null;
  90978. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90979. this._onBeforeActiveMeshesEvaluationObserver = null;
  90980. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90981. this._onAfterActiveMeshesEvaluationObserver = null;
  90982. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90983. this._onBeforeRenderTargetsRenderObserver = null;
  90984. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90985. this._onAfterRenderTargetsRenderObserver = null;
  90986. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90987. this._onBeforeAnimationsObserver = null;
  90988. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90989. this._onBeforeParticlesRenderingObserver = null;
  90990. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90991. this._onAfterParticlesRenderingObserver = null;
  90992. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90993. this._onBeforeSpritesRenderingObserver = null;
  90994. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90995. this._onAfterSpritesRenderingObserver = null;
  90996. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90997. this._onBeforeDrawPhaseObserver = null;
  90998. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90999. this._onAfterDrawPhaseObserver = null;
  91000. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  91001. this._onBeforePhysicsObserver = null;
  91002. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  91003. this._onAfterPhysicsObserver = null;
  91004. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  91005. this._onAfterAnimationsObserver = null;
  91006. this.scene = null;
  91007. };
  91008. return SceneInstrumentation;
  91009. }());
  91010. BABYLON.SceneInstrumentation = SceneInstrumentation;
  91011. })(BABYLON || (BABYLON = {}));
  91012. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  91013. "use strict";
  91014. var BABYLON;
  91015. (function (BABYLON) {
  91016. var _TimeToken = /** @class */ (function () {
  91017. function _TimeToken() {
  91018. this._timeElapsedQueryEnded = false;
  91019. }
  91020. return _TimeToken;
  91021. }());
  91022. BABYLON._TimeToken = _TimeToken;
  91023. })(BABYLON || (BABYLON = {}));
  91024. //# sourceMappingURL=babylon.timeToken.js.map
  91025. "use strict";
  91026. var BABYLON;
  91027. (function (BABYLON) {
  91028. /**
  91029. * Background material defines definition.
  91030. * @ignore Mainly internal Use
  91031. */
  91032. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  91033. __extends(BackgroundMaterialDefines, _super);
  91034. /**
  91035. * Constructor of the defines.
  91036. */
  91037. function BackgroundMaterialDefines() {
  91038. var _this = _super.call(this) || this;
  91039. /**
  91040. * True if the diffuse texture is in use.
  91041. */
  91042. _this.DIFFUSE = false;
  91043. /**
  91044. * The direct UV channel to use.
  91045. */
  91046. _this.DIFFUSEDIRECTUV = 0;
  91047. /**
  91048. * True if the diffuse texture is in gamma space.
  91049. */
  91050. _this.GAMMADIFFUSE = false;
  91051. /**
  91052. * True if the diffuse texture has opacity in the alpha channel.
  91053. */
  91054. _this.DIFFUSEHASALPHA = false;
  91055. /**
  91056. * True if you want the material to fade to transparent at grazing angle.
  91057. */
  91058. _this.OPACITYFRESNEL = false;
  91059. /**
  91060. * True if an extra blur needs to be added in the reflection.
  91061. */
  91062. _this.REFLECTIONBLUR = false;
  91063. /**
  91064. * True if you want the material to fade to reflection at grazing angle.
  91065. */
  91066. _this.REFLECTIONFRESNEL = false;
  91067. /**
  91068. * True if you want the material to falloff as far as you move away from the scene center.
  91069. */
  91070. _this.REFLECTIONFALLOFF = false;
  91071. /**
  91072. * False if the current Webgl implementation does not support the texture lod extension.
  91073. */
  91074. _this.TEXTURELODSUPPORT = false;
  91075. /**
  91076. * True to ensure the data are premultiplied.
  91077. */
  91078. _this.PREMULTIPLYALPHA = false;
  91079. /**
  91080. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  91081. */
  91082. _this.USERGBCOLOR = false;
  91083. /**
  91084. * True to add noise in order to reduce the banding effect.
  91085. */
  91086. _this.NOISE = false;
  91087. /**
  91088. * is the reflection texture in BGR color scheme?
  91089. * Mainly used to solve a bug in ios10 video tag
  91090. */
  91091. _this.REFLECTIONBGR = false;
  91092. _this.IMAGEPROCESSING = false;
  91093. _this.VIGNETTE = false;
  91094. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  91095. _this.VIGNETTEBLENDMODEOPAQUE = false;
  91096. _this.TONEMAPPING = false;
  91097. _this.CONTRAST = false;
  91098. _this.COLORCURVES = false;
  91099. _this.COLORGRADING = false;
  91100. _this.COLORGRADING3D = false;
  91101. _this.SAMPLER3DGREENDEPTH = false;
  91102. _this.SAMPLER3DBGRMAP = false;
  91103. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  91104. _this.EXPOSURE = false;
  91105. _this.GRAIN = false;
  91106. // Reflection.
  91107. _this.REFLECTION = false;
  91108. _this.REFLECTIONMAP_3D = false;
  91109. _this.REFLECTIONMAP_SPHERICAL = false;
  91110. _this.REFLECTIONMAP_PLANAR = false;
  91111. _this.REFLECTIONMAP_CUBIC = false;
  91112. _this.REFLECTIONMAP_PROJECTION = false;
  91113. _this.REFLECTIONMAP_SKYBOX = false;
  91114. _this.REFLECTIONMAP_EXPLICIT = false;
  91115. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91116. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91117. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91118. _this.INVERTCUBICMAP = false;
  91119. _this.REFLECTIONMAP_OPPOSITEZ = false;
  91120. _this.LODINREFLECTIONALPHA = false;
  91121. _this.GAMMAREFLECTION = false;
  91122. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  91123. // Default BJS.
  91124. _this.MAINUV1 = false;
  91125. _this.MAINUV2 = false;
  91126. _this.UV1 = false;
  91127. _this.UV2 = false;
  91128. _this.CLIPPLANE = false;
  91129. _this.POINTSIZE = false;
  91130. _this.FOG = false;
  91131. _this.NORMAL = false;
  91132. _this.NUM_BONE_INFLUENCERS = 0;
  91133. _this.BonesPerMesh = 0;
  91134. _this.INSTANCES = false;
  91135. _this.SHADOWFLOAT = false;
  91136. _this.rebuild();
  91137. return _this;
  91138. }
  91139. return BackgroundMaterialDefines;
  91140. }(BABYLON.MaterialDefines));
  91141. /**
  91142. * Background material used to create an efficient environement around your scene.
  91143. */
  91144. var BackgroundMaterial = /** @class */ (function (_super) {
  91145. __extends(BackgroundMaterial, _super);
  91146. /**
  91147. * Instantiates a Background Material in the given scene
  91148. * @param name The friendly name of the material
  91149. * @param scene The scene to add the material to
  91150. */
  91151. function BackgroundMaterial(name, scene) {
  91152. var _this = _super.call(this, name, scene) || this;
  91153. /**
  91154. * Key light Color (multiply against the R channel of the environement texture)
  91155. */
  91156. _this.primaryColor = BABYLON.Color3.White();
  91157. /**
  91158. * Key light Level (allowing HDR output of the background)
  91159. */
  91160. _this.primaryLevel = 1;
  91161. /**
  91162. * Secondary light Color (multiply against the G channel of the environement texture)
  91163. */
  91164. _this.secondaryColor = BABYLON.Color3.Gray();
  91165. /**
  91166. * Secondary light Level (allowing HDR output of the background)
  91167. */
  91168. _this.secondaryLevel = 1;
  91169. /**
  91170. * Tertiary light Color (multiply against the B channel of the environement texture)
  91171. */
  91172. _this.tertiaryColor = BABYLON.Color3.Black();
  91173. /**
  91174. * Tertiary light Level (allowing HDR output of the background)
  91175. */
  91176. _this.tertiaryLevel = 1;
  91177. /**
  91178. * Reflection Texture used in the material.
  91179. * Should be author in a specific way for the best result (refer to the documentation).
  91180. */
  91181. _this.reflectionTexture = null;
  91182. /**
  91183. * Reflection Texture level of blur.
  91184. *
  91185. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  91186. * texture twice.
  91187. */
  91188. _this.reflectionBlur = 0;
  91189. /**
  91190. * Diffuse Texture used in the material.
  91191. * Should be author in a specific way for the best result (refer to the documentation).
  91192. */
  91193. _this.diffuseTexture = null;
  91194. _this._shadowLights = null;
  91195. /**
  91196. * Specify the list of lights casting shadow on the material.
  91197. * All scene shadow lights will be included if null.
  91198. */
  91199. _this.shadowLights = null;
  91200. /**
  91201. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  91202. * soft lighting on the background.
  91203. */
  91204. _this.shadowBlurScale = 1;
  91205. /**
  91206. * Helps adjusting the shadow to a softer level if required.
  91207. * 0 means black shadows and 1 means no shadows.
  91208. */
  91209. _this.shadowLevel = 0;
  91210. /**
  91211. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  91212. * It is usually zero but might be interesting to modify according to your setup.
  91213. */
  91214. _this.sceneCenter = BABYLON.Vector3.Zero();
  91215. /**
  91216. * This helps specifying that the material is falling off to the sky box at grazing angle.
  91217. * This helps ensuring a nice transition when the camera goes under the ground.
  91218. */
  91219. _this.opacityFresnel = true;
  91220. /**
  91221. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  91222. * This helps adding a mirror texture on the ground.
  91223. */
  91224. _this.reflectionFresnel = false;
  91225. /**
  91226. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  91227. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  91228. */
  91229. _this.reflectionFalloffDistance = 0.0;
  91230. /**
  91231. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  91232. */
  91233. _this.reflectionAmount = 1.0;
  91234. /**
  91235. * This specifies the weight of the reflection at grazing angle.
  91236. */
  91237. _this.reflectionReflectance0 = 0.05;
  91238. /**
  91239. * This specifies the weight of the reflection at a perpendicular point of view.
  91240. */
  91241. _this.reflectionReflectance90 = 0.5;
  91242. /**
  91243. * Helps to directly use the maps channels instead of their level.
  91244. */
  91245. _this.useRGBColor = true;
  91246. /**
  91247. * This helps reducing the banding effect that could occur on the background.
  91248. */
  91249. _this.enableNoise = false;
  91250. _this._fovMultiplier = 1.0;
  91251. /**
  91252. * Enable the FOV adjustment feature controlled by fovMultiplier.
  91253. * @type {boolean}
  91254. */
  91255. _this.useEquirectangularFOV = false;
  91256. _this._maxSimultaneousLights = 4;
  91257. /**
  91258. * Number of Simultaneous lights allowed on the material.
  91259. */
  91260. _this.maxSimultaneousLights = 4;
  91261. /**
  91262. * Keep track of the image processing observer to allow dispose and replace.
  91263. */
  91264. _this._imageProcessingObserver = null;
  91265. /**
  91266. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  91267. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  91268. */
  91269. _this.switchToBGR = false;
  91270. // Temp values kept as cache in the material.
  91271. _this._renderTargets = new BABYLON.SmartArray(16);
  91272. _this._reflectionControls = BABYLON.Vector4.Zero();
  91273. // Setup the default processing configuration to the scene.
  91274. _this._attachImageProcessingConfiguration(null);
  91275. _this.getRenderTargetTextures = function () {
  91276. _this._renderTargets.reset();
  91277. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  91278. _this._renderTargets.push(_this._diffuseTexture);
  91279. }
  91280. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  91281. _this._renderTargets.push(_this._reflectionTexture);
  91282. }
  91283. return _this._renderTargets;
  91284. };
  91285. return _this;
  91286. }
  91287. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  91288. /**
  91289. * Sets the reflection reflectance fresnel values according to the default standard
  91290. * empirically know to work well :-)
  91291. */
  91292. set: function (value) {
  91293. var reflectionWeight = value;
  91294. if (reflectionWeight < 0.5) {
  91295. reflectionWeight = reflectionWeight * 2.0;
  91296. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  91297. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  91298. }
  91299. else {
  91300. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  91301. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  91302. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  91303. }
  91304. },
  91305. enumerable: true,
  91306. configurable: true
  91307. });
  91308. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  91309. /**
  91310. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91311. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  91312. * Recommended to be keep at 1.0 except for special cases.
  91313. */
  91314. get: function () {
  91315. return this._fovMultiplier;
  91316. },
  91317. set: function (value) {
  91318. if (isNaN(value)) {
  91319. value = 1.0;
  91320. }
  91321. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  91322. },
  91323. enumerable: true,
  91324. configurable: true
  91325. });
  91326. /**
  91327. * Attaches a new image processing configuration to the PBR Material.
  91328. * @param configuration (if null the scene configuration will be use)
  91329. */
  91330. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91331. var _this = this;
  91332. if (configuration === this._imageProcessingConfiguration) {
  91333. return;
  91334. }
  91335. // Detaches observer.
  91336. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91337. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91338. }
  91339. // Pick the scene configuration if needed.
  91340. if (!configuration) {
  91341. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91342. }
  91343. else {
  91344. this._imageProcessingConfiguration = configuration;
  91345. }
  91346. // Attaches observer.
  91347. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91348. _this._markAllSubMeshesAsImageProcessingDirty();
  91349. });
  91350. };
  91351. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91352. /**
  91353. * Gets the image processing configuration used either in this material.
  91354. */
  91355. get: function () {
  91356. return this._imageProcessingConfiguration;
  91357. },
  91358. /**
  91359. * Sets the Default image processing configuration used either in the this material.
  91360. *
  91361. * If sets to null, the scene one is in use.
  91362. */
  91363. set: function (value) {
  91364. this._attachImageProcessingConfiguration(value);
  91365. // Ensure the effect will be rebuilt.
  91366. this._markAllSubMeshesAsTexturesDirty();
  91367. },
  91368. enumerable: true,
  91369. configurable: true
  91370. });
  91371. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91372. /**
  91373. * Gets wether the color curves effect is enabled.
  91374. */
  91375. get: function () {
  91376. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91377. },
  91378. /**
  91379. * Sets wether the color curves effect is enabled.
  91380. */
  91381. set: function (value) {
  91382. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91383. },
  91384. enumerable: true,
  91385. configurable: true
  91386. });
  91387. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91388. /**
  91389. * Gets wether the color grading effect is enabled.
  91390. */
  91391. get: function () {
  91392. return this.imageProcessingConfiguration.colorGradingEnabled;
  91393. },
  91394. /**
  91395. * Gets wether the color grading effect is enabled.
  91396. */
  91397. set: function (value) {
  91398. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91399. },
  91400. enumerable: true,
  91401. configurable: true
  91402. });
  91403. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91404. /**
  91405. * Gets wether tonemapping is enabled or not.
  91406. */
  91407. get: function () {
  91408. return this._imageProcessingConfiguration.toneMappingEnabled;
  91409. },
  91410. /**
  91411. * Sets wether tonemapping is enabled or not
  91412. */
  91413. set: function (value) {
  91414. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91415. },
  91416. enumerable: true,
  91417. configurable: true
  91418. });
  91419. ;
  91420. ;
  91421. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91422. /**
  91423. * The camera exposure used on this material.
  91424. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91425. * This corresponds to a photographic exposure.
  91426. */
  91427. get: function () {
  91428. return this._imageProcessingConfiguration.exposure;
  91429. },
  91430. /**
  91431. * The camera exposure used on this material.
  91432. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91433. * This corresponds to a photographic exposure.
  91434. */
  91435. set: function (value) {
  91436. this._imageProcessingConfiguration.exposure = value;
  91437. },
  91438. enumerable: true,
  91439. configurable: true
  91440. });
  91441. ;
  91442. ;
  91443. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91444. /**
  91445. * Gets The camera contrast used on this material.
  91446. */
  91447. get: function () {
  91448. return this._imageProcessingConfiguration.contrast;
  91449. },
  91450. /**
  91451. * Sets The camera contrast used on this material.
  91452. */
  91453. set: function (value) {
  91454. this._imageProcessingConfiguration.contrast = value;
  91455. },
  91456. enumerable: true,
  91457. configurable: true
  91458. });
  91459. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91460. /**
  91461. * Gets the Color Grading 2D Lookup Texture.
  91462. */
  91463. get: function () {
  91464. return this._imageProcessingConfiguration.colorGradingTexture;
  91465. },
  91466. /**
  91467. * Sets the Color Grading 2D Lookup Texture.
  91468. */
  91469. set: function (value) {
  91470. this.imageProcessingConfiguration.colorGradingTexture = value;
  91471. },
  91472. enumerable: true,
  91473. configurable: true
  91474. });
  91475. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91476. /**
  91477. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91478. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91479. * 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;
  91480. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91481. */
  91482. get: function () {
  91483. return this.imageProcessingConfiguration.colorCurves;
  91484. },
  91485. /**
  91486. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91487. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91488. * 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;
  91489. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91490. */
  91491. set: function (value) {
  91492. this.imageProcessingConfiguration.colorCurves = value;
  91493. },
  91494. enumerable: true,
  91495. configurable: true
  91496. });
  91497. /**
  91498. * The entire material has been created in order to prevent overdraw.
  91499. * @returns false
  91500. */
  91501. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91502. return true;
  91503. };
  91504. /**
  91505. * The entire material has been created in order to prevent overdraw.
  91506. * @returns true if blending is enable
  91507. */
  91508. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91509. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91510. };
  91511. /**
  91512. * Checks wether the material is ready to be rendered for a given mesh.
  91513. * @param mesh The mesh to render
  91514. * @param subMesh The submesh to check against
  91515. * @param useInstances Specify wether or not the material is used with instances
  91516. * @returns true if all the dependencies are ready (Textures, Effects...)
  91517. */
  91518. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91519. var _this = this;
  91520. if (useInstances === void 0) { useInstances = false; }
  91521. if (subMesh.effect && this.isFrozen) {
  91522. if (this._wasPreviouslyReady) {
  91523. return true;
  91524. }
  91525. }
  91526. if (!subMesh._materialDefines) {
  91527. subMesh._materialDefines = new BackgroundMaterialDefines();
  91528. }
  91529. var scene = this.getScene();
  91530. var defines = subMesh._materialDefines;
  91531. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91532. if (defines._renderId === scene.getRenderId()) {
  91533. return true;
  91534. }
  91535. }
  91536. var engine = scene.getEngine();
  91537. // Lights
  91538. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91539. defines._needNormals = true;
  91540. // Textures
  91541. if (defines._areTexturesDirty) {
  91542. defines._needUVs = false;
  91543. if (scene.texturesEnabled) {
  91544. if (scene.getEngine().getCaps().textureLOD) {
  91545. defines.TEXTURELODSUPPORT = true;
  91546. }
  91547. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91548. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91549. return false;
  91550. }
  91551. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91552. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91553. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91554. defines.OPACITYFRESNEL = this._opacityFresnel;
  91555. }
  91556. else {
  91557. defines.DIFFUSE = false;
  91558. defines.DIFFUSEHASALPHA = false;
  91559. defines.GAMMADIFFUSE = false;
  91560. defines.OPACITYFRESNEL = false;
  91561. }
  91562. var reflectionTexture = this._reflectionTexture;
  91563. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91564. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91565. return false;
  91566. }
  91567. defines.REFLECTION = true;
  91568. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91569. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91570. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91571. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91572. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91573. defines.REFLECTIONBGR = this.switchToBGR;
  91574. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91575. defines.INVERTCUBICMAP = true;
  91576. }
  91577. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91578. switch (reflectionTexture.coordinatesMode) {
  91579. case BABYLON.Texture.CUBIC_MODE:
  91580. case BABYLON.Texture.INVCUBIC_MODE:
  91581. defines.REFLECTIONMAP_CUBIC = true;
  91582. break;
  91583. case BABYLON.Texture.EXPLICIT_MODE:
  91584. defines.REFLECTIONMAP_EXPLICIT = true;
  91585. break;
  91586. case BABYLON.Texture.PLANAR_MODE:
  91587. defines.REFLECTIONMAP_PLANAR = true;
  91588. break;
  91589. case BABYLON.Texture.PROJECTION_MODE:
  91590. defines.REFLECTIONMAP_PROJECTION = true;
  91591. break;
  91592. case BABYLON.Texture.SKYBOX_MODE:
  91593. defines.REFLECTIONMAP_SKYBOX = true;
  91594. break;
  91595. case BABYLON.Texture.SPHERICAL_MODE:
  91596. defines.REFLECTIONMAP_SPHERICAL = true;
  91597. break;
  91598. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91599. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91600. break;
  91601. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91602. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91603. break;
  91604. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91605. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91606. break;
  91607. }
  91608. if (this.reflectionFresnel) {
  91609. defines.REFLECTIONFRESNEL = true;
  91610. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91611. this._reflectionControls.x = this.reflectionAmount;
  91612. this._reflectionControls.y = this.reflectionReflectance0;
  91613. this._reflectionControls.z = this.reflectionReflectance90;
  91614. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91615. }
  91616. else {
  91617. defines.REFLECTIONFRESNEL = false;
  91618. defines.REFLECTIONFALLOFF = false;
  91619. }
  91620. }
  91621. else {
  91622. defines.REFLECTION = false;
  91623. defines.REFLECTIONFALLOFF = false;
  91624. defines.REFLECTIONBLUR = false;
  91625. defines.REFLECTIONMAP_3D = false;
  91626. defines.REFLECTIONMAP_SPHERICAL = false;
  91627. defines.REFLECTIONMAP_PLANAR = false;
  91628. defines.REFLECTIONMAP_CUBIC = false;
  91629. defines.REFLECTIONMAP_PROJECTION = false;
  91630. defines.REFLECTIONMAP_SKYBOX = false;
  91631. defines.REFLECTIONMAP_EXPLICIT = false;
  91632. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91633. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91634. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91635. defines.INVERTCUBICMAP = false;
  91636. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91637. defines.LODINREFLECTIONALPHA = false;
  91638. defines.GAMMAREFLECTION = false;
  91639. }
  91640. }
  91641. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91642. defines.USERGBCOLOR = this._useRGBColor;
  91643. defines.NOISE = this._enableNoise;
  91644. }
  91645. if (defines._areImageProcessingDirty) {
  91646. if (!this._imageProcessingConfiguration.isReady()) {
  91647. return false;
  91648. }
  91649. this._imageProcessingConfiguration.prepareDefines(defines);
  91650. }
  91651. // Misc.
  91652. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91653. // Values that need to be evaluated on every frame
  91654. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91655. // Attribs
  91656. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91657. if (mesh) {
  91658. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91659. mesh.createNormals(true);
  91660. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91661. }
  91662. }
  91663. }
  91664. // Get correct effect
  91665. if (defines.isDirty) {
  91666. defines.markAsProcessed();
  91667. scene.resetCachedMaterial();
  91668. // Fallbacks
  91669. var fallbacks = new BABYLON.EffectFallbacks();
  91670. if (defines.FOG) {
  91671. fallbacks.addFallback(0, "FOG");
  91672. }
  91673. if (defines.POINTSIZE) {
  91674. fallbacks.addFallback(1, "POINTSIZE");
  91675. }
  91676. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91677. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91678. fallbacks.addCPUSkinningFallback(0, mesh);
  91679. }
  91680. //Attributes
  91681. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91682. if (defines.NORMAL) {
  91683. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91684. }
  91685. if (defines.UV1) {
  91686. attribs.push(BABYLON.VertexBuffer.UVKind);
  91687. }
  91688. if (defines.UV2) {
  91689. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91690. }
  91691. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91692. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91693. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91694. "vFogInfos", "vFogColor", "pointSize",
  91695. "vClipPlane", "mBones",
  91696. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91697. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91698. "shadowLevel", "alpha",
  91699. "vBackgroundCenter", "vReflectionControl",
  91700. "vDiffuseInfos", "diffuseMatrix",
  91701. ];
  91702. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91703. var uniformBuffers = ["Material", "Scene"];
  91704. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91705. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91706. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91707. uniformsNames: uniforms,
  91708. uniformBuffersNames: uniformBuffers,
  91709. samplers: samplers,
  91710. defines: defines,
  91711. maxSimultaneousLights: this._maxSimultaneousLights
  91712. });
  91713. var onCompiled = function (effect) {
  91714. if (_this.onCompiled) {
  91715. _this.onCompiled(effect);
  91716. }
  91717. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91718. };
  91719. var join = defines.toString();
  91720. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91721. attributes: attribs,
  91722. uniformsNames: uniforms,
  91723. uniformBuffersNames: uniformBuffers,
  91724. samplers: samplers,
  91725. defines: join,
  91726. fallbacks: fallbacks,
  91727. onCompiled: onCompiled,
  91728. onError: this.onError,
  91729. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91730. }, engine), defines);
  91731. this.buildUniformLayout();
  91732. }
  91733. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91734. return false;
  91735. }
  91736. defines._renderId = scene.getRenderId();
  91737. this._wasPreviouslyReady = true;
  91738. return true;
  91739. };
  91740. /**
  91741. * Build the uniform buffer used in the material.
  91742. */
  91743. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91744. // Order is important !
  91745. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91746. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91747. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91748. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91749. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91750. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91751. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91752. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91753. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91754. this._uniformBuffer.addUniform("pointSize", 1);
  91755. this._uniformBuffer.addUniform("shadowLevel", 1);
  91756. this._uniformBuffer.addUniform("alpha", 1);
  91757. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91758. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91759. this._uniformBuffer.create();
  91760. };
  91761. /**
  91762. * Unbind the material.
  91763. */
  91764. BackgroundMaterial.prototype.unbind = function () {
  91765. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91766. this._uniformBuffer.setTexture("diffuseSampler", null);
  91767. }
  91768. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91769. this._uniformBuffer.setTexture("reflectionSampler", null);
  91770. }
  91771. _super.prototype.unbind.call(this);
  91772. };
  91773. /**
  91774. * Bind only the world matrix to the material.
  91775. * @param world The world matrix to bind.
  91776. */
  91777. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91778. this._activeEffect.setMatrix("world", world);
  91779. };
  91780. /**
  91781. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91782. * @param world The world matrix to bind.
  91783. * @param subMesh The submesh to bind for.
  91784. */
  91785. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91786. var scene = this.getScene();
  91787. var defines = subMesh._materialDefines;
  91788. if (!defines) {
  91789. return;
  91790. }
  91791. var effect = subMesh.effect;
  91792. if (!effect) {
  91793. return;
  91794. }
  91795. this._activeEffect = effect;
  91796. // Matrices
  91797. this.bindOnlyWorldMatrix(world);
  91798. // Bones
  91799. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91800. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91801. if (mustRebind) {
  91802. this._uniformBuffer.bindToEffect(effect, "Material");
  91803. this.bindViewProjection(effect);
  91804. var reflectionTexture = this._reflectionTexture;
  91805. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91806. // Texture uniforms
  91807. if (scene.texturesEnabled) {
  91808. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91809. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91810. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91811. }
  91812. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91813. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91814. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91815. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91816. }
  91817. }
  91818. if (this.shadowLevel > 0) {
  91819. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91820. }
  91821. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91822. // Point size
  91823. if (this.pointsCloud) {
  91824. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91825. }
  91826. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91827. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91828. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91829. }
  91830. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91831. // Textures
  91832. if (scene.texturesEnabled) {
  91833. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91834. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91835. }
  91836. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91837. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91838. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91839. }
  91840. else if (!defines.REFLECTIONBLUR) {
  91841. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91842. }
  91843. else {
  91844. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91845. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91846. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91847. }
  91848. if (defines.REFLECTIONFRESNEL) {
  91849. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91850. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91851. }
  91852. }
  91853. }
  91854. // Clip plane
  91855. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91856. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91857. }
  91858. if (mustRebind || !this.isFrozen) {
  91859. if (scene.lightsEnabled) {
  91860. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91861. }
  91862. // View
  91863. this.bindView(effect);
  91864. // Fog
  91865. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91866. // image processing
  91867. this._imageProcessingConfiguration.bind(this._activeEffect);
  91868. }
  91869. this._uniformBuffer.update();
  91870. this._afterBind(mesh);
  91871. };
  91872. /**
  91873. * Dispose the material.
  91874. * @param forceDisposeEffect Force disposal of the associated effect.
  91875. * @param forceDisposeTextures Force disposal of the associated textures.
  91876. */
  91877. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91878. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91879. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91880. if (forceDisposeTextures) {
  91881. if (this.diffuseTexture) {
  91882. this.diffuseTexture.dispose();
  91883. }
  91884. if (this.reflectionTexture) {
  91885. this.reflectionTexture.dispose();
  91886. }
  91887. }
  91888. this._renderTargets.dispose();
  91889. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91890. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91891. }
  91892. _super.prototype.dispose.call(this, forceDisposeEffect);
  91893. };
  91894. /**
  91895. * Clones the material.
  91896. * @param name The cloned name.
  91897. * @returns The cloned material.
  91898. */
  91899. BackgroundMaterial.prototype.clone = function (name) {
  91900. var _this = this;
  91901. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91902. };
  91903. /**
  91904. * Serializes the current material to its JSON representation.
  91905. * @returns The JSON representation.
  91906. */
  91907. BackgroundMaterial.prototype.serialize = function () {
  91908. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91909. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91910. return serializationObject;
  91911. };
  91912. /**
  91913. * Gets the class name of the material
  91914. * @returns "BackgroundMaterial"
  91915. */
  91916. BackgroundMaterial.prototype.getClassName = function () {
  91917. return "BackgroundMaterial";
  91918. };
  91919. /**
  91920. * Parse a JSON input to create back a background material.
  91921. * @param source The JSON data to parse
  91922. * @param scene The scene to create the parsed material in
  91923. * @param rootUrl The root url of the assets the material depends upon
  91924. * @returns the instantiated BackgroundMaterial.
  91925. */
  91926. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91927. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91928. };
  91929. /**
  91930. * Standard reflectance value at parallel view angle.
  91931. */
  91932. BackgroundMaterial.StandardReflectance0 = 0.05;
  91933. /**
  91934. * Standard reflectance value at grazing angle.
  91935. */
  91936. BackgroundMaterial.StandardReflectance90 = 0.5;
  91937. __decorate([
  91938. BABYLON.serializeAsColor3()
  91939. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91940. __decorate([
  91941. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91942. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91943. __decorate([
  91944. BABYLON.serialize()
  91945. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91946. __decorate([
  91947. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91948. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91949. __decorate([
  91950. BABYLON.serializeAsColor3()
  91951. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91952. __decorate([
  91953. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91954. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91955. __decorate([
  91956. BABYLON.serialize()
  91957. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91958. __decorate([
  91959. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91960. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91961. __decorate([
  91962. BABYLON.serializeAsColor3()
  91963. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91964. __decorate([
  91965. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91966. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91967. __decorate([
  91968. BABYLON.serialize()
  91969. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91970. __decorate([
  91971. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91972. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91973. __decorate([
  91974. BABYLON.serializeAsTexture()
  91975. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91976. __decorate([
  91977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91978. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91979. __decorate([
  91980. BABYLON.serialize()
  91981. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91982. __decorate([
  91983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91984. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91985. __decorate([
  91986. BABYLON.serializeAsTexture()
  91987. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91988. __decorate([
  91989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91990. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91991. __decorate([
  91992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91993. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91994. __decorate([
  91995. BABYLON.serialize()
  91996. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91997. __decorate([
  91998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91999. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  92000. __decorate([
  92001. BABYLON.serialize()
  92002. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  92003. __decorate([
  92004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92005. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  92006. __decorate([
  92007. BABYLON.serializeAsVector3()
  92008. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  92009. __decorate([
  92010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92011. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  92012. __decorate([
  92013. BABYLON.serialize()
  92014. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  92015. __decorate([
  92016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92017. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  92018. __decorate([
  92019. BABYLON.serialize()
  92020. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  92021. __decorate([
  92022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92023. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  92024. __decorate([
  92025. BABYLON.serialize()
  92026. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  92027. __decorate([
  92028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92029. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  92030. __decorate([
  92031. BABYLON.serialize()
  92032. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  92033. __decorate([
  92034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92035. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  92036. __decorate([
  92037. BABYLON.serialize()
  92038. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  92039. __decorate([
  92040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92041. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  92042. __decorate([
  92043. BABYLON.serialize()
  92044. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  92045. __decorate([
  92046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92047. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  92048. __decorate([
  92049. BABYLON.serialize()
  92050. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  92051. __decorate([
  92052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92053. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  92054. __decorate([
  92055. BABYLON.serialize()
  92056. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  92057. __decorate([
  92058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92059. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  92060. __decorate([
  92061. BABYLON.serialize()
  92062. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  92063. __decorate([
  92064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92065. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  92066. __decorate([
  92067. BABYLON.serializeAsImageProcessingConfiguration()
  92068. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  92069. return BackgroundMaterial;
  92070. }(BABYLON.PushMaterial));
  92071. BABYLON.BackgroundMaterial = BackgroundMaterial;
  92072. })(BABYLON || (BABYLON = {}));
  92073. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  92074. "use strict";
  92075. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92076. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92077. s = arguments[i];
  92078. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92079. t[p] = s[p];
  92080. }
  92081. return t;
  92082. };
  92083. var BABYLON;
  92084. (function (BABYLON) {
  92085. /**
  92086. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  92087. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  92088. * It also helps with the default setup of your imageProcessing configuration.
  92089. */
  92090. var EnvironmentHelper = /** @class */ (function () {
  92091. /**
  92092. * constructor
  92093. * @param options
  92094. * @param scene The scene to add the material to
  92095. */
  92096. function EnvironmentHelper(options, scene) {
  92097. var _this = this;
  92098. this._errorHandler = function (message, exception) {
  92099. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  92100. };
  92101. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  92102. this._scene = scene;
  92103. this.onErrorObservable = new BABYLON.Observable();
  92104. this._setupBackground();
  92105. this._setupImageProcessing();
  92106. }
  92107. /**
  92108. * Creates the default options for the helper.
  92109. */
  92110. EnvironmentHelper._getDefaultOptions = function () {
  92111. return {
  92112. createGround: true,
  92113. groundSize: 15,
  92114. groundTexture: this._groundTextureCDNUrl,
  92115. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92116. groundOpacity: 0.9,
  92117. enableGroundShadow: true,
  92118. groundShadowLevel: 0.5,
  92119. enableGroundMirror: false,
  92120. groundMirrorSizeRatio: 0.3,
  92121. groundMirrorBlurKernel: 64,
  92122. groundMirrorAmount: 1,
  92123. groundMirrorFresnelWeight: 1,
  92124. groundMirrorFallOffDistance: 0,
  92125. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  92126. groundYBias: 0.00001,
  92127. createSkybox: true,
  92128. skyboxSize: 20,
  92129. skyboxTexture: this._skyboxTextureCDNUrl,
  92130. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92131. backgroundYRotation: 0,
  92132. sizeAuto: true,
  92133. rootPosition: BABYLON.Vector3.Zero(),
  92134. setupImageProcessing: true,
  92135. environmentTexture: this._environmentTextureCDNUrl,
  92136. cameraExposure: 0.8,
  92137. cameraContrast: 1.2,
  92138. toneMappingEnabled: true,
  92139. };
  92140. };
  92141. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  92142. /**
  92143. * Gets the root mesh created by the helper.
  92144. */
  92145. get: function () {
  92146. return this._rootMesh;
  92147. },
  92148. enumerable: true,
  92149. configurable: true
  92150. });
  92151. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  92152. /**
  92153. * Gets the skybox created by the helper.
  92154. */
  92155. get: function () {
  92156. return this._skybox;
  92157. },
  92158. enumerable: true,
  92159. configurable: true
  92160. });
  92161. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  92162. /**
  92163. * Gets the skybox texture created by the helper.
  92164. */
  92165. get: function () {
  92166. return this._skyboxTexture;
  92167. },
  92168. enumerable: true,
  92169. configurable: true
  92170. });
  92171. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  92172. /**
  92173. * Gets the skybox material created by the helper.
  92174. */
  92175. get: function () {
  92176. return this._skyboxMaterial;
  92177. },
  92178. enumerable: true,
  92179. configurable: true
  92180. });
  92181. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  92182. /**
  92183. * Gets the ground mesh created by the helper.
  92184. */
  92185. get: function () {
  92186. return this._ground;
  92187. },
  92188. enumerable: true,
  92189. configurable: true
  92190. });
  92191. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  92192. /**
  92193. * Gets the ground texture created by the helper.
  92194. */
  92195. get: function () {
  92196. return this._groundTexture;
  92197. },
  92198. enumerable: true,
  92199. configurable: true
  92200. });
  92201. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  92202. /**
  92203. * Gets the ground mirror created by the helper.
  92204. */
  92205. get: function () {
  92206. return this._groundMirror;
  92207. },
  92208. enumerable: true,
  92209. configurable: true
  92210. });
  92211. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  92212. /**
  92213. * Gets the ground mirror render list to helps pushing the meshes
  92214. * you wish in the ground reflection.
  92215. */
  92216. get: function () {
  92217. if (this._groundMirror) {
  92218. return this._groundMirror.renderList;
  92219. }
  92220. return null;
  92221. },
  92222. enumerable: true,
  92223. configurable: true
  92224. });
  92225. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  92226. /**
  92227. * Gets the ground material created by the helper.
  92228. */
  92229. get: function () {
  92230. return this._groundMaterial;
  92231. },
  92232. enumerable: true,
  92233. configurable: true
  92234. });
  92235. /**
  92236. * Updates the background according to the new options
  92237. * @param options
  92238. */
  92239. EnvironmentHelper.prototype.updateOptions = function (options) {
  92240. var newOptions = __assign({}, this._options, options);
  92241. if (this._ground && !newOptions.createGround) {
  92242. this._ground.dispose();
  92243. this._ground = null;
  92244. }
  92245. if (this._groundMaterial && !newOptions.createGround) {
  92246. this._groundMaterial.dispose();
  92247. this._groundMaterial = null;
  92248. }
  92249. if (this._groundTexture) {
  92250. if (this._options.groundTexture != newOptions.groundTexture) {
  92251. this._groundTexture.dispose();
  92252. this._groundTexture = null;
  92253. }
  92254. }
  92255. if (this._skybox && !newOptions.createSkybox) {
  92256. this._skybox.dispose();
  92257. this._skybox = null;
  92258. }
  92259. if (this._skyboxMaterial && !newOptions.createSkybox) {
  92260. this._skyboxMaterial.dispose();
  92261. this._skyboxMaterial = null;
  92262. }
  92263. if (this._skyboxTexture) {
  92264. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  92265. this._skyboxTexture.dispose();
  92266. this._skyboxTexture = null;
  92267. }
  92268. }
  92269. if (this._groundMirror && !newOptions.enableGroundMirror) {
  92270. this._groundMirror.dispose();
  92271. this._groundMirror = null;
  92272. }
  92273. if (this._scene.environmentTexture) {
  92274. if (this._options.environmentTexture != newOptions.environmentTexture) {
  92275. this._scene.environmentTexture.dispose();
  92276. }
  92277. }
  92278. this._options = newOptions;
  92279. this._setupBackground();
  92280. this._setupImageProcessing();
  92281. };
  92282. /**
  92283. * Sets the primary color of all the available elements.
  92284. * @param color
  92285. */
  92286. EnvironmentHelper.prototype.setMainColor = function (color) {
  92287. if (this.groundMaterial) {
  92288. this.groundMaterial.primaryColor = color;
  92289. }
  92290. if (this.skyboxMaterial) {
  92291. this.skyboxMaterial.primaryColor = color;
  92292. }
  92293. if (this.groundMirror) {
  92294. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  92295. }
  92296. };
  92297. /**
  92298. * Setup the image processing according to the specified options.
  92299. */
  92300. EnvironmentHelper.prototype._setupImageProcessing = function () {
  92301. if (this._options.setupImageProcessing) {
  92302. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  92303. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  92304. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  92305. this._setupEnvironmentTexture();
  92306. }
  92307. };
  92308. /**
  92309. * Setup the environment texture according to the specified options.
  92310. */
  92311. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  92312. if (this._scene.environmentTexture) {
  92313. return;
  92314. }
  92315. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  92316. this._scene.environmentTexture = this._options.environmentTexture;
  92317. return;
  92318. }
  92319. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  92320. this._scene.environmentTexture = environmentTexture;
  92321. };
  92322. /**
  92323. * Setup the background according to the specified options.
  92324. */
  92325. EnvironmentHelper.prototype._setupBackground = function () {
  92326. if (!this._rootMesh) {
  92327. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92328. }
  92329. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92330. var sceneSize = this._getSceneSize();
  92331. if (this._options.createGround) {
  92332. this._setupGround(sceneSize);
  92333. this._setupGroundMaterial();
  92334. this._setupGroundDiffuseTexture();
  92335. if (this._options.enableGroundMirror) {
  92336. this._setupGroundMirrorTexture(sceneSize);
  92337. }
  92338. this._setupMirrorInGroundMaterial();
  92339. }
  92340. if (this._options.createSkybox) {
  92341. this._setupSkybox(sceneSize);
  92342. this._setupSkyboxMaterial();
  92343. this._setupSkyboxReflectionTexture();
  92344. }
  92345. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92346. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92347. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92348. };
  92349. /**
  92350. * Get the scene sizes according to the setup.
  92351. */
  92352. EnvironmentHelper.prototype._getSceneSize = function () {
  92353. var _this = this;
  92354. var groundSize = this._options.groundSize;
  92355. var skyboxSize = this._options.skyboxSize;
  92356. var rootPosition = this._options.rootPosition;
  92357. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92358. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92359. }
  92360. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92361. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92362. });
  92363. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92364. if (this._options.sizeAuto) {
  92365. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92366. this._scene.activeCamera.upperRadiusLimit) {
  92367. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92368. skyboxSize = groundSize;
  92369. }
  92370. var sceneDiagonalLenght = sceneDiagonal.length();
  92371. if (sceneDiagonalLenght > groundSize) {
  92372. groundSize = sceneDiagonalLenght * 2;
  92373. skyboxSize = groundSize;
  92374. }
  92375. // 10 % bigger.
  92376. groundSize *= 1.1;
  92377. skyboxSize *= 1.5;
  92378. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92379. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92380. }
  92381. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92382. };
  92383. /**
  92384. * Setup the ground according to the specified options.
  92385. */
  92386. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92387. var _this = this;
  92388. if (!this._ground) {
  92389. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92390. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92391. this._ground.parent = this._rootMesh;
  92392. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92393. }
  92394. this._ground.receiveShadows = this._options.enableGroundShadow;
  92395. };
  92396. /**
  92397. * Setup the ground material according to the specified options.
  92398. */
  92399. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92400. if (!this._groundMaterial) {
  92401. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92402. }
  92403. this._groundMaterial.alpha = this._options.groundOpacity;
  92404. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92405. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92406. this._groundMaterial.primaryLevel = 1;
  92407. this._groundMaterial.primaryColor = this._options.groundColor;
  92408. this._groundMaterial.secondaryLevel = 0;
  92409. this._groundMaterial.tertiaryLevel = 0;
  92410. this._groundMaterial.useRGBColor = false;
  92411. this._groundMaterial.enableNoise = true;
  92412. if (this._ground) {
  92413. this._ground.material = this._groundMaterial;
  92414. }
  92415. };
  92416. /**
  92417. * Setup the ground diffuse texture according to the specified options.
  92418. */
  92419. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92420. if (!this._groundMaterial) {
  92421. return;
  92422. }
  92423. if (this._groundTexture) {
  92424. return;
  92425. }
  92426. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92427. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92428. return;
  92429. }
  92430. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92431. diffuseTexture.gammaSpace = false;
  92432. diffuseTexture.hasAlpha = true;
  92433. this._groundMaterial.diffuseTexture = diffuseTexture;
  92434. };
  92435. /**
  92436. * Setup the ground mirror texture according to the specified options.
  92437. */
  92438. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92439. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92440. if (!this._groundMirror) {
  92441. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92442. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92443. this._groundMirror.anisotropicFilteringLevel = 1;
  92444. this._groundMirror.wrapU = wrapping;
  92445. this._groundMirror.wrapV = wrapping;
  92446. this._groundMirror.gammaSpace = false;
  92447. if (this._groundMirror.renderList) {
  92448. for (var i = 0; i < this._scene.meshes.length; i++) {
  92449. var mesh = this._scene.meshes[i];
  92450. if (mesh !== this._ground &&
  92451. mesh !== this._skybox &&
  92452. mesh !== this._rootMesh) {
  92453. this._groundMirror.renderList.push(mesh);
  92454. }
  92455. }
  92456. }
  92457. }
  92458. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92459. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92460. };
  92461. /**
  92462. * Setup the ground to receive the mirror texture.
  92463. */
  92464. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92465. if (this._groundMaterial) {
  92466. this._groundMaterial.reflectionTexture = this._groundMirror;
  92467. this._groundMaterial.reflectionFresnel = true;
  92468. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92469. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92470. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92471. }
  92472. };
  92473. /**
  92474. * Setup the skybox according to the specified options.
  92475. */
  92476. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92477. var _this = this;
  92478. if (!this._skybox) {
  92479. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92480. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92481. }
  92482. this._skybox.parent = this._rootMesh;
  92483. };
  92484. /**
  92485. * Setup the skybox material according to the specified options.
  92486. */
  92487. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92488. if (!this._skybox) {
  92489. return;
  92490. }
  92491. if (!this._skyboxMaterial) {
  92492. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92493. }
  92494. this._skyboxMaterial.useRGBColor = false;
  92495. this._skyboxMaterial.primaryLevel = 1;
  92496. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92497. this._skyboxMaterial.secondaryLevel = 0;
  92498. this._skyboxMaterial.tertiaryLevel = 0;
  92499. this._skyboxMaterial.enableNoise = true;
  92500. this._skybox.material = this._skyboxMaterial;
  92501. };
  92502. /**
  92503. * Setup the skybox reflection texture according to the specified options.
  92504. */
  92505. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92506. if (!this._skyboxMaterial) {
  92507. return;
  92508. }
  92509. if (this._skyboxTexture) {
  92510. return;
  92511. }
  92512. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92513. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92514. return;
  92515. }
  92516. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92517. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92518. this._skyboxTexture.gammaSpace = false;
  92519. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92520. };
  92521. /**
  92522. * Dispose all the elements created by the Helper.
  92523. */
  92524. EnvironmentHelper.prototype.dispose = function () {
  92525. if (this._groundMaterial) {
  92526. this._groundMaterial.dispose(true, true);
  92527. }
  92528. if (this._skyboxMaterial) {
  92529. this._skyboxMaterial.dispose(true, true);
  92530. }
  92531. this._rootMesh.dispose(false);
  92532. };
  92533. /**
  92534. * Default ground texture URL.
  92535. */
  92536. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92537. /**
  92538. * Default skybox texture URL.
  92539. */
  92540. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92541. /**
  92542. * Default environment texture URL.
  92543. */
  92544. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92545. return EnvironmentHelper;
  92546. }());
  92547. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92548. })(BABYLON || (BABYLON = {}));
  92549. //# sourceMappingURL=babylon.environmentHelper.js.map
  92550. "use strict";
  92551. var BABYLON;
  92552. (function (BABYLON) {
  92553. /**
  92554. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92555. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92556. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92557. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92558. */
  92559. var VideoDome = /** @class */ (function (_super) {
  92560. __extends(VideoDome, _super);
  92561. /**
  92562. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92563. * @param name Element's name, child elements will append suffixes for their own names.
  92564. * @param urlsOrVideo
  92565. * @param options An object containing optional or exposed sub element properties:
  92566. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92567. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92568. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92569. * @param options **loop=true** Automatically loop video on end.
  92570. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92571. */
  92572. function VideoDome(name, urlsOrVideo, options, scene) {
  92573. var _this = _super.call(this, name, scene) || this;
  92574. // set defaults and manage values
  92575. name = name || "videoDome";
  92576. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92577. options.clickToPlay = Boolean(options.clickToPlay);
  92578. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92579. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92580. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92581. // create
  92582. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92583. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92584. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92585. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92586. flat: false,
  92587. radius: options.size,
  92588. subdivisions: options.resolution,
  92589. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92590. }, scene);
  92591. // configure material
  92592. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92593. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92594. material.reflectionTexture = _this._videoTexture;
  92595. material.useEquirectangularFOV = true;
  92596. material.fovMultiplier = 1.0;
  92597. // configure mesh
  92598. _this._mesh.material = material;
  92599. _this._mesh.parent = _this;
  92600. // optional configuration
  92601. if (options.clickToPlay) {
  92602. scene.onPointerUp = function () {
  92603. _this._videoTexture.video.play();
  92604. };
  92605. }
  92606. return _this;
  92607. }
  92608. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92609. /**
  92610. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92611. * Also see the options.resolution property.
  92612. */
  92613. get: function () {
  92614. return this._material.fovMultiplier;
  92615. },
  92616. set: function (value) {
  92617. this._material.fovMultiplier = value;
  92618. },
  92619. enumerable: true,
  92620. configurable: true
  92621. });
  92622. /**
  92623. * Releases resources associated with this node.
  92624. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92625. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92626. */
  92627. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92628. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92629. this._videoTexture.dispose();
  92630. this._mesh.dispose();
  92631. this._material.dispose();
  92632. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92633. };
  92634. return VideoDome;
  92635. }(BABYLON.Node));
  92636. BABYLON.VideoDome = VideoDome;
  92637. })(BABYLON || (BABYLON = {}));
  92638. //# sourceMappingURL=babylon.videoDome.js.map
  92639. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=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\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\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#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\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\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.,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 float stopFactor;\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) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\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;\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*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\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#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\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 vec3 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.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\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{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  92640. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\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 computeShadowWithPoissonSamplingCube(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 computeShadowWithPoissonSampling(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#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(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#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,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#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  92641. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92642. globalObject["BABYLON"] = BABYLON
  92643. return BABYLON;
  92644. });